[英]How do I connect to a SQL database from C#?
我正在嘗試為我的家庭網絡編寫本地程序管理和安裝系統,我想我已經確定了技術:
但是我不確定具體用於將C#連接到數據庫的具體內容。 .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 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的模式和實踐企業庫 。 您將專門使用數據訪問應用程序塊 。
來自MSDN的摘錄:
數據訪問應用程序塊具有以下優點:
- 它使用ADO.NET 2.0提供的功能,您可以使用ADO.NET功能和應用程序塊的功能。
- 它減少了編寫樣板代碼以執行標准任務的需要。
- 它有助於在應用程序內和整個企業內維護一致的數據訪問實踐。
- 它減少了更改數據庫類型的難度。
- 它使開發人員無需為不同類型的數據庫學習不同的編程模型。
- 它減少了開發人員在將應用程序移植到不同類型的數據庫時必須編寫的代碼量。
我已經使用這種方法多年了,到目前為止它已經非常成功了。 祝好運!
當然,你可以使用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();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.