下面是要用戶名和密碼連接數據庫的操作:
一、定義連接字符串,用來鏈接SQL Server
string str_con = "server=.(服務器名稱一般為 . );database=WordBook(數據庫名稱);uid=sa(服務器登錄名);pwd=123(服務器密碼)";
二、有了鏈接字符串之后,開始數據庫操作
1、數據庫查詢
定義了一個查詢方法,用來調用:
public DataSet queryDatabase(string sql) //sql是查詢語句
{
//儲存數據的工具初始化
DataSet ds = new DataSet();
//相當於鏈接數據庫的一個工具類(連接字符串)
using (SqlConnection con = new SqlConnection(str_con))
{
con.Open(); //打開
//用SqlConnection工具鏈接數據庫,在通過sql查詢語句查詢結果現存入sql適配器
SqlDataAdapter sda = new SqlDataAdapter(sql,con); //(查詢語句和連接工具)
sda.Fill(ds); //將適配器數據存入DataSet工具中
con.Close(); //用完關閉SqlConnection工具
return ds;
}
}
在需要查詢數據庫的地方調用此方法:
private void query() {
//查詢WordBook表中,book_key字段數值為7的那一行數據
//string sql = "select * from Word_Book where book_key='7'";
string sql = "select * from Word_Book "; //查詢全表
DataSet ds = help.queryDatabase(sql); //查詢到數據
DataTable dt = ds.Tables[0]; //把查到的數據存入數據表中
sqlDataResult.DataSource = dt; //把數據賦值給gridView展示(全表)
// string str=dt.Rows[0][1].ToString();//查找表中某一個內容
// MessageBox.Show(str);
}
2、數據庫添加、刪除、修改
C#中數據庫的添加、刪除、修改用的是同斷代碼,所以定義了一個方法,用來調用:
public int changeSqlData(String sql)
{
using(SqlConnection con=new SqlConnection(str_con))
{
con.Open();
//操作數據庫的工具SqlCommand
SqlCommand cmd = new SqlCommand(sql, con);//(操作語句和鏈接工具)
int i=cmd.ExecuteNonQuery();//執行操作返回影響行數()
con.Close();
return i;
}
}
在需要操作數據庫的地方調用此方法:
①數據庫添加:
private void btn_add_Click(object sender, EventArgs e)
{
//sql添加數據 insert into 表名(字段,字段...) values(‘內容’,‘內容’...)
string sql = "insert into Word_Book(book_word_CN,book_word_JP,book_word_Roma,book_nominal," +
"book_gloze) values('" + book_word_CN.Text.Trim()+"','"+ book_word_JP .Text.Trim() + "','"
+ book_word_Roma .Text.Trim() + "','"+ book_nominal.Text.Trim() + "','" + book_gloze.Text.Trim() + "')";
int i=help.changeSqlData(sql);
if (i == 0) MessageBox.Show("添加失敗", "提示:");
else MessageBox.Show("添加成功", "提示:");
}
②數據庫刪除:
private void btn_delete_Click(object sender, EventArgs e)
{
//根據同個字段中不同內容刪除多行
//delete from Word_Book where book_key in (1,2,3)
//sql刪除數據delete 表名 where 字段='內容'單個條件用or鏈接,多個條件用and鏈接
string sql = "delete from Word_Book where book_key='"+book_key.Text.Trim()+"'";
int i=help.changeSqlData(sql);
if (i == 0) MessageBox.Show("刪除失敗", "提示:");
else MessageBox.Show("刪除成功", "提示:");
}
②數據庫更新:
private void btn_update_Click(object sender, EventArgs e)
{
//根據條件修改多個字段內容
//update 表名 set 字段='內容', 字段='內容' where 條件字段='內容'
string sql = "update Word_Book set book_word_CN='"+book_word_CN.Text.Trim()+
"', book_word_JP='"+book_word_JP.Text.Trim()+"'where book_key='" + book_key.Text.Trim()+"'";
int i = help.changeSqlData(sql);
if (i == 0) MessageBox.Show("修改失敗", "提示:");
else MessageBox.Show("修改成功", "提示:");
}
3、數據庫事務操作數據庫
用數據庫事務相當於把數據庫操作捆綁執行,只要其中一條sql語句失敗,直接返回,不進行數據庫操作,只有全部執行正確,才會更新數據庫。
定義了一個查詢方法,用來調用:
public bool openTrans(List<String> lst)
{
using (SqlConnection con=new SqlConnection(str_con))
{
con.Open();
//開啟事務
SqlTransaction trans = con.BeginTransaction();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;//添加鏈接工具
cmd.Transaction = trans;//添加事務
try
{
for (int i = 0; i < lst.Count; i++)
{
string sql=lst[i].ToString();//獲取sql語句
cmd.CommandText = sql;//添加sql語句
cmd.ExecuteNonQuery();//執行
}
trans.Commit();//執行完成之后提交
return true;
}
catch(Exception e)
{
//執行sql語句失敗,事務回滾
trans.Rollback();
return false;
}
finally
{
con.Close();
}
}
}
在需要操作數據庫的地方調用此方法:
private void transql_Click(object sender, EventArgs e)
{
List<string> lst = new List<string>();
lst.Add("update Word_Book set book_word_CN='" + book_word_CN.Text.Trim() +
"', book_word_JP='" + book_word_JP.Text.Trim() + "'where book_key='" + book_key.Text.Trim() + "'");
lst.Add("update Word_Book set book_word_Roma='" + book_word_Roma.Text.Trim() +
"', book_nominal='" + book_nominal.Text.Trim() + "'where book_key='" + book_key.Text.Trim() + "'");
Boolean isOk= help.openTrans(lst);
if (!isOk) MessageBox.Show("修改失敗", "提示:");
else MessageBox.Show("修改成功", "提示:");
}
C#增刪改查操作完成,想要方便可以自定義一個類,把所有的方法寫在里面,當有用到的時候可以初始化該類的實例用來調用類里的方法
在VS2012中新建一個Windows窗口應用程序,並在Form中放置DataGridView和Button兩個控件,在Button的單擊響應事件中連接數據庫:
private void button1_Click(object sender, EventArgs e) { String connsql = "server=.;database=MyDBName;integrated security=SSPI"; // 數據庫連接字符串,database設置為自己的數據庫名,以Windows身份驗證 try { using (SqlConnection conn = new SqlConnection()) { conn.ConnectionString = connsql; conn.Open(); // 打開數據庫連接 String sql = "select * from student"; // 查詢語句 SqlDataAdapter myda = new SqlDataAdapter(sql, conn); // 實例化適配器 DataTable dt = new DataTable(); // 實例化數據表 myda.Fill(dt); // 保存數據 dataGridView1.DataSource = dt; // 設置到DataGridView中 conn.Close(); // 關閉數據庫連接 } } catch (Exception ex) { MessageBox.Show("錯誤信息:" + ex.Message, "出現錯誤"); } }
該類中封裝了關於數據庫連接和操作的方法,各個功能模塊在需進行數據庫操作時只需調用相應的函數:

//引入的命名空間 using System.Data.SqlClient;//用於SQL Sever數據訪問的命名空間 using System.Data; //DataSet類的命名空間 using System.Windows.Forms; //DataGridView控件類的命名空間 //執行指定的SQL命令語句(insert,delete,update等),並返回命令所影響的行數 public static int executeCommand(string sqlStr) { SqlConnection sqlConnection1 = new SqlConnection("server=dell-PC;database=11071312HotelSys;uid=sa;pwd=xiaoyi9421");//創建數據庫連接(字符串中是我個人的數據庫信息) sqlConnection1.Open(); //打開數據庫連接 SqlCommand sqlCommand1 = new SqlCommand(sqlStr, sqlConnection1); //執行SQL命令 int Succnum = sqlCommand1.ExecuteNonQuery(); return Succnum; } //查詢(select)指定的數據記錄(多行多列),並填充到數據控件DataGridView中 public static void queryDataToGrid(string sqlStr, DataGridView dataGridView1) { SqlConnection sqlConnection1 = new SqlConnection("server=dell-PC;database=11071312HotelSys;uid=sa;pwd=xiaoyi9421");//創建數據庫連接 SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter(sqlStr, sqlConnection1);//利用已創建好的sqlConnection1,創建數據適配器sqlDataAdapter1 DataSet dataSet1 = new DataSet(); //創建數據集對象 sqlDataAdapter1.Fill(dataSet1); //執行查詢,查詢的結果存放在數據集里 dataGridView1.DataSource = dataSet1.Tables[0]; //把數據集中的查詢結果綁定到dataGridView1中 } //查詢(select)指定的數據(單個數據,假設為string類型),並返回 public static string queryData(string sqlStr) { SqlConnection sqlConnection1 = new SqlConnection("server=dell-PC;database=11071312HotelSys;uid=sa;pwd=xiaoyi9421");//創建數據庫連接 SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter(sqlStr, sqlConnection1);//利用已創建好的sqlConnection1,創建數據適配器sqlDataAdapter1 DataSet dataSet1 = new DataSet(); //創建數據集對象 sqlDataAdapter1.Fill(dataSet1); //執行查詢,查詢的結果存放在數據集里 return dataSet1.Tables[0].Rows[0]["列名"].ToString(); //把查詢結果的第一行指定列下的數據以string類型返回 }
當在各個功能模塊中需要進行數據庫操作時,只需指定要執行的SQL語句,調用一下數據庫工具類中的方法即可實現,下面給了一些基本的的SQL操作(單表)

//增 sqlStr = "insert into 表名( 列名1 , 列名2 )values( 插入值1 , 插入值2 )"; //執行指定的SQL命令語句,並返回命令所影響的行數 int Succnum = MyTool.executeCommand(sqlStr); if (Succnum > 0) MessageBox.Show("錄入成功"); //刪 sqlStr = "delete from 表名 where 刪除條件"; int Succnum = MyTool.executeCommand(sqlStr); if (Succnum > 0) MessageBox.Show("刪除成功"); //改 sqlStr = "update 表名 set 列名1 = 更新值1 , 列名2 = 更新值2"; int Succnum = MyTool.executeCommand(sqlStr); if (Succnum > 0) MessageBox.Show("更新成功"); //查一組數據 sqlStr = "select 列名1 , 列名2 from 表名 where 查詢表達式"; MyTool.queryDataToGrid(sqlStr, dataGridView1);//填充到數據控件DataGridView中 //查單個數據 sqlStr = "select 列名 from 表名 where 查詢表達式"; textBox1.Text = MyTool.queryData(sqlStr);//填充到文本框textBox1中