如何从C#连接到SQL数据库?

我正在尝试为我的家庭网络编写本地程序管理和安装系统,我想我已经确定了技术:

  • C#/。NET / WPF为客户端
  • Lua用于安装脚本支持(通过LuaInterface)
  • SQL Server Express用于维护程序数据库

但是我不确定具体用于将C#连接到数据库的具体内容。 .NET框架中是否有内置的东西? 如果您对我应该用于与所述数据库进行交互的内容有何建议,则可获得奖励积分。

查看

  • ADO.NET教程简介
  • ADO.NET教程第1课
  • ADO.NET简介

我相信还有更多的东西 – 只需谷歌“ADO.NET”和“教程”……

更新:

如果要连接到本地SQL Server Express,并连接到“Northwind”数据库,并从“Customers”表中读取前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的实际应用!

至于连接字符串的详细信息 – 您可以使用哪些选项以及它应该是什么样的,请查看Connection Strings网站 – 它有大量的示例和解释。

的SqlConnection

对象就是这样做的。

例如:

 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中获得的任何function。

您可以使用ADO.Net和System.Data.SqlClient命名空间。 我会建议你选择entity framework(ORM)。 请在下面找到entity framework的链接

http://thedatafarm.com/LearnEntityFramework/tutorials/creating-an-ado-net-entity-framework-entity-data-model/

http://thedatafarm.com/LearnEntityFramework/tutorials/use-an-entity-framework-entity-as-a-winforms-data-source/

我建议使用Microsoft的模式和实践企业库 。 您将专门使用数据访问应用程序块 。

来自MSDN的摘录:

数据访问应用程序块具有以下优点:

  • 它使用ADO.NET 2.0提供的function,您可以使用ADO.NETfunction和应用程序块的function。
  • 它减少了编写样板代码以执行标准任务的需要。
  • 它有助于在应用程序内和整个企业内维护一致的数据访问实践。
  • 它减少了更改数据库类型的难度。
  • 它使开发人员无需为不同类型的数据库学习不同的编程模型。
  • 它减少了开发人员在将应用程序移植到不同类型的数据库时必须编写的代码量。

我已经使用这种方法多年了,到目前为止它已经非常成功。 祝好运!

目前,连接数据库并在C#中执行查询的最简单方法是LinqToSQL 。 与使用“老派”ADO连接相比,它将为您节省很多麻烦。

当然,你可以使用System.Data.SqlClient中的类,尽管大多数人都会使用ORM。 我用的是LLBLGen Pro 。

我希望这有助于尝试这些..

@类

 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"); } } 

@MAIN ACCESS

 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(); } } }