public DataTable Read()
{
DataTable dt =new DataTable();//新建表
dt.Columns.Add("col_1");//新建表中的列
dt.Columns.Add("col_2");
string ConnectionString ="data source=localhost;initial catalog=pubs;user id=sa;password=sa";
SqlConnection Conn= new SqlConnection(ConnectionString);
if (Conn.State==ConnectionState.Open)
{
Conn.Close();
}
Conn.ConnectionString=ConnectionString;
Conn.Open();
try
{
SqlCommand cmd=new SqlCommand("Select * from tab_name",Conn);
SqlDataReader myReader =cmd.ExecuteReader();//執行SQL語句的真正查詢了
int a=0;
int b=0;//用來接收已經查詢出來的字段
while (myReader.Read()) 每次循環查到的一行 如果有N行就循環N次而已
{
DataRow dr =dt.NewRow();//每循環一次新建一行
dr[0] =myReader.GetInt32(0).ToString(); 表示接收第一個字段(string型)
dr[1] =myReader.GetInt32(1).ToString();
dt.Rows.Add(dr);//每次循環把dr加進去
}
myReader.Close();
Conn.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
return dt;
}
c#連接SQL數據庫
c#連接SQL數據庫代碼
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.