我正在尝试为我的家庭网络编写一个本地程序管理和安装系统,我认为我已经确定了技术:
- 客户端的 C#/.NET/WPF
- Lua 用于安装脚本支持(通过 LuaInterface)
- 用于维护程序数据库的 SQL Server Express
但是我不确定我将使用什么来将 C# 连接到数据库。.NET 框架中是否为此内置了一些东西?如果您对我应该使用什么来与所述数据库进行交互有建议,则可以加分。
我正在尝试为我的家庭网络编写一个本地程序管理和安装系统,我认为我已经确定了技术:
但是我不确定我将使用什么来将 C# 连接到数据库。.NET 框架中是否为此内置了一些东西?如果您对我应该使用什么来与所述数据库进行交互有建议,则可以加分。
查看
我敢肯定还有更多内容 - 只需在谷歌上搜索“ADO.NET”和“Tutorial”......
更新:
如果要连接到本地 SQL Server Express,并连接到“Northwind”数据库,并从“客户”表中读取前 5 个客户,则必须执行以下操作:
string connectionString = "server=(local)\SQLExpress;database=Northwind;integrated Security=SSPI;";
using(SqlConnection _con = new SqlConnection(connectionString))
{
string queryStatement = "SELECT TOP 5 * FROM dbo.Customers ORDER BY CustomerID";
using(SqlCommand _cmd = new SqlCommand(queryStatement, _con))
{
DataTable customerTable = new DataTable("Top5Customers");
SqlDataAdapter _dap = new SqlDataAdapter(_cmd);
_con.Open();
_dap.Fill(customerTable);
_con.Close();
}
}
现在,您将在 DataTable 中拥有 Northwind 数据库中的所有 5 个顶级客户,您可以检查、打印、操作它们——无论您想做什么。
这就是 ADO.NET 的实际应用!
至于连接字符串的详细信息——你可以使用哪些选项以及它应该是什么样子,请查看连接字符串网站——它有大量的示例和解释。
马克
对象是为此而制作的。
例如:
SqlConnection conn = new SqlConnection(
"Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");
或者
SqlConnection conn = new SqlConnection(
"Data Source=DatabaseServer; Initial Catalog=Northwind; User ID=YourUserID; Password=YourPassword");
conn.Open(); // opens the database connection
编辑:
完成所有工作后,您必须通过以下方式关闭连接
conn.Close();
数据源:标识服务器。可以是本地机器、机器域名或 IP 地址。
初始目录:数据库名称。
集成安全性:设置为 SSPI 以与用户的 Windows 登录建立连接
用户 ID:在 SQL Server 中配置的用户名。
密码:与 SQL Server 用户 ID 匹配的密码。
要连接到 SQL Server Express,您只需要System.Data
.NET 程序集,它是一个标准的程序集。只需使用SqlXXX
类,你就完成了。
但是,编写普通的 ADO.NET 代码非常无聊,因此使用 ORM 或重量较轻的结果集映射器(如BLToolkit )非常常见。
最后,考虑使用 SQL Server CE。这是一个完全符合 ACID 的单文件嵌入式数据库引擎,它支持几乎所有您可以从 SQL RDBMS 中获得的功能。
目前,连接到数据库并在 C# 中执行查询的最简单方法是LinqToSQL。与使用“老式”ADO 连接相比,它会为您省去很多麻烦。
您可以使用相同的 ADO.Net 和 System.Data.SqlClient 命名空间。我会建议您使用实体框架(ORM)。请在下面找到实体框架演练的链接
我建议使用Microsoft 的 Patterns & Practices Enterprise Library。您将专门使用The Data Access Application Block。
摘自 MSDN:
数据访问应用程序块提供以下好处:
- 它使用 ADO.NET 2.0 提供的功能,通过它,您可以将 ADO.NET 功能与应用程序块的功能一起使用。
- 它减少了编写样板代码来执行标准任务的需要。
- 它有助于在应用程序内和整个企业中保持一致的数据访问实践。
- 它减少了更改数据库类型的困难。
- 它使开发人员无需为不同类型的数据库学习不同的编程模型。
- 它减少了开发人员在将应用程序移植到不同类型的数据库时必须编写的代码量。
我已经使用这种方法很多年了,到目前为止它非常成功。祝你好运!
我希望这将有助于尝试这些..
@班级
using System.Data;
using System.Data.SqlClient;
namespace WindowsFormsApplication2
{
class clsDB
{
public SqlDataAdapter mDataAdapter = new SqlDataAdapter();
public DataSet mDataSet = new DataSet();
public SqlConnection mConn;
public clsDB()
{
mConn = new SqlConnection("Data Source=(the data source);Initial Catalog=sample;User ID=(the id);Password=(the password)");
}
public void SQLDB(string strSQL)
{
try
{
mDataAdapter = new SqlDataAdapter(new SqlCommand(strSQL, mConn));
mDataSet = new DataSet();
mDataAdapter.Fill(mDataSet);
}
catch (Exception ex)
{
throw ex;
}
finally
{
mConn.Close();
}
}
public void ClearRes()
{
mDataAdapter.Dispose();
mDataAdapter = null;
mDataSet.Dispose();
if (mConn.State != ConnectionState.Closed)
{
mConn.Close();
}
}
}
}
@登录
public partial class Login : Form
{
clsDB x = new clsDB();
public Login()
{
InitializeComponent();
}
private void btnSubmit_Click(object sender, EventArgs e)
{
x.SQLDB("select * from tbl_accounts where u_username ='" + txtUser.Text + "' and u_password ='" + txtPass.Text + "'");
if (x.mDataSet.Tables[0].Rows.Count > 0)
{
Main a = new Main();
this.Hide();
a.Show();
}
else
{
MessageBox.Show("wrong username or password");
}
}
@主访问
namespace WindowsFormsApplication2
{
public partial class Main : Form
{
clsDB x = new clsDB();
public Main()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
x.SQLDB("insert into tbl_info (u_lastname, u_firstname, u_middlename) values ('" + atxtLN.Text + "','" + atxtFN.Text + "','" + atxtFN.Text + "')");
fillgrid();
}
private void Main_Load(object sender, EventArgs e)
{
x.SQLDB(" select * from tbl_info ");
dgv1.DataSource = x.mDataSet.Tables[0];
fillgrid();
}
void fillgrid()
{
x.SQLDB("select * from tbl_info");
dgv1.DataSource = null;
dgv1.DataSource = x.mDataSet.Tables[0];
}
void search()
{
x.SQLDB("SELECT * from tbl_info where u_id like '" + etxtID.Text + "%' order by u_id");
if (x.mDataSet.Tables[0].Rows.Count > 0)
{
x.mDataAdapter.Fill(x.mDataSet, "tbl_info");
dgv1.DataSource = x.mDataSet.Tables["tbl_info"].DefaultView;
etxtLN.Text = dgv1.Rows[dgv1.CurrentRow.Index].Cells["u_lastname"].Value.ToString();
etxtFN.Text = dgv1.Rows[dgv1.CurrentRow.Index].Cells["u_firstname"].Value.ToString();
etxtMN.Text = dgv1.Rows[dgv1.CurrentRow.Index].Cells["u_middlename"].Value.ToString();
}
else if (etxtID.Text == "Type User ID to Edit")
{
etxtLN.Text = "";
etxtFN.Text = "";
etxtMN.Text = "";
}
else
{
etxtLN.Text = "";
etxtFN.Text = "";
etxtMN.Text = "";
}
}
private void etxtID_TextChanged(object sender, EventArgs e)
{
}
private void etxtID_Enter(object sender, EventArgs e)
{
etxtID.Text = "";
etxtID.ForeColor = Color.Black;
}
private void etxtID_Leave(object sender, EventArgs e)
{
if (etxtID.Text == "")
{
etxtID.ForeColor = Color.Gray;
etxtID.Text = "Type User ID to Edit";
x.SQLDB(" select * from tbl_info ");
dgv1.DataSource = x.mDataSet.Tables[0];
fillgrid();
}
}
private void etxtID_KeyUp(object sender, KeyEventArgs e)
{
search();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
x.SQLDB("UPDATE tbl_info set u_lastname ='" + etxtLN.Text + "', u_firstname ='" + etxtFN.Text + "', u_middlename ='" + etxtMN.Text + "' where u_id =" + etxtID.Text);
MessageBox.Show("Operation Successful!");
fillgrid();
}
private void btnDelete_Click(object sender, EventArgs e)
{
x.SQLDB("delete from tbl_info where u_id =" + dtxtID.Text + "");
MessageBox.Show("Operation Successful!");
fillgrid();
}
}
}
当然,您可以只使用 System.Data.SqlClient 中的类,尽管大多数人会使用 ORM。我使用LLBLGen Pro。
您可以使用https://github.com/MohamadParsa/AdoDbConnection.Net并将该项目用作解决方案中的项目参考并享受。此外,您可以DBConnection.cs
在项目中浏览文件并复制类或方法。但是...为了建立连接或断开连接以表达您可以使用:
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
string _ErorrString = "";
string _InternalErorrString = "";
private void Connect()
{
cmd.Connection = con;
da.SelectCommand = cmd;
try
{
string cs = "";
cs = @"Data source=.\SQLEXPRESS;Attachdbfilename=|DataDirectory|\"
+ DataBbaseName + ".mdf;Integrated security=true;user Instance=true";
con.ConnectionString = cs;
con.Open();
}
catch (Exception ex)
{
_ErorrString += "Erorr NO. : 100" + ", connection error.";
_InternalErorrString += ex.Message;
}
}
private void Disconnect()
{
con.Close();
}
并执行命令并获得结果:
public DataSet RunAndGet(string sql)
{
//first, make a connection
Connect();
//to hold and return results
DataSet dataSet = new DataSet();
try
{
//set command
cmd.CommandText = sql;
//run and fill results into the dataset
da.Fill(dataSet);
}
catch (Exception ex)
{
_ErorrString += "Erorr NO. : 101" + ", internal error.";
_InternalErorrString += ex.Message;
}
//finally closes connection
Disconnect();
return dataSet;
}