1、添加引用using System.Data;using System.Data.SqlData;2、建立于數(shù)據(jù)庫的連接,建議將它做成一個方法,方便多次利用。string sqlconnection = "data source = "注解1";database = 注解2;uid = "注解3";pwd ="注解4"";(其實還有很多種寫法)可以參考http://www.cnblogs.com/delphinet/archive/2011/06/24/2088765.html3、經(jīng)常用到的對象有:SqlConnection,SqlAdapter,SqlCommand、Dataset、DataGrid和 DataReader等,以SqlConnection,SqlAdapter,SqlCommand、Dataset、DataGrid對象,操作 SQL的實例數(shù)據(jù)庫Northwind中的Categorys表為例說明(假定數(shù)據(jù)庫在本地,數(shù)據(jù)庫訪問的用戶名為user,密碼為123456):接下來做一下四個操作的實現(xiàn)
第一、查詢數(shù)據(jù):
string MyConn="server=127.0.0.1;uid=user;pwd=123456;database=Northwind;Trusted_Connection=no";//定義數(shù)據(jù)庫連接參數(shù)
SqlConnection MyConnection=new SqlConnection(MyConn);//定義一個數(shù)據(jù)連接實例
SqlCommand MyCommand=new SqlCommand("SELECT CategoryID, CategoryName, Description FROM Categories",MyConnection); //定義一個數(shù)據(jù)庫操作指令
SqlDataAdapter SelectAdapter=new SqlDataAdapter();//定義一個數(shù)據(jù)適配器
SelectAdapter.SelectCommand=MyCommand;//定義數(shù)據(jù)適配器的操作指令
DataSet MyDataSet=new DataSet();//定義一個數(shù)據(jù)集
MyConnection.Open();//打開數(shù)據(jù)庫連接
SelectAdapter.SelectCommand.ExecuteNonQuery();//執(zhí)行數(shù)據(jù)庫查詢指令
MyConnection.Close();//關(guān)閉數(shù)據(jù)庫
SelectAdapter.Fill(MyDataSet);//填充數(shù)據(jù)集
DataGrid1.DataSource=MyDataSet;
DataGrid1.DataBind();//將數(shù)據(jù)表格用數(shù)據(jù)集中的數(shù)據(jù)填充
第二、添加數(shù)據(jù)
string MyConn="server=127.0.0.1;uid=user;pwd=123456;database=Northwind;Trusted_Connection=no";
SqlConnection MyConnection=new SqlConnection(MyConn);
string MyInsert="insert into Categories(CategoryName, Description)values(''"+Convert.ToString(TextBox2.Text)+"'',''"+Convert.ToString(TextBox3.Text)+"'')";
SqlCommand MyCommand=new SqlCommand(MyInsert,MyConnection);
try//異常處理
{
MyConnection.Open();
MyCommand.ExecuteNonQuery();
MyConnection.Close();
}
catch(Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
第三、修改數(shù)據(jù)
string categoryName=TextBox2.Text;
string categoryDescription=TextBox3.Text;
string MyConn="server=127.0.0.1;uid=user;pwd=123456;database=Northwind;Trusted_Connection=no";
SqlConnection MyConnection=new SqlConnection(MyConn);
string MyUpdate="Update Categories set CategoryName=''"+categoryName+"'',Description=''"+categoryDescription+"'' where CategoryID="+TextBox1.Text;
SqlCommand MyCommand=new SqlCommand(MyUpdate,MyConnection);
try
{
MyConnection.Open();
MyCommand.ExecuteNonQuery();
MyConnection.Close();
TextBox1.Text="";
}
catch(Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
第四、刪除數(shù)據(jù)
string MyConn="server=127.0.0.1;uid=user;pwd=123456;database=Northwind;Trusted_Connection=no";
SqlConnection MyConnection=new SqlConnection(MyConn);
string MyDelete="Delete from Categories where CategoryID="+TextBox1.Text;
SqlCommand MyCommand=new SqlCommand(MyDelete,MyConnection);
try
{
MyConnection.Open();
MyCommand.ExecuteNonQuery();
MyConnection.Close();
TextBox1.Text="";
}
catch(Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}