1.命名空間要加入
using System.Data.SqlClient;2.重頭戲來了
SqlConnection conn = new SqlConnection("server=*name or IP;database=資料庫名稱;uid=使用者帳號;pwd=使用者名稱");整理:*SqlExpress比較特別 除IP還要加上\\SQLEXPRESSconn.open();
如140.116.123.123\\SQLEXPRESS
SqlCommand s_com = new SqlCommand();
s_com.CommandText = "SQL語法"; //語法如 select * from table_xxx
s_com.Connection = conn;
SqlDataReader s_read = s_com.ExecuteReader();
while ( s_read.Read() ) // 迴圈會執行到沒有下一筆資料為止
{
textbox.Text +=s_read["欄位名稱"].ToString(); //這裡只是舉例,會將每次讀到的row的特定欄位值接在textbox後面
}
s_read.Close();
conn.Close();
//判斷是不是有符合條件的ROW可以用 if ( s_read.HASROWS )
//s_read.HASROWS會回傳true or false
new SqlConnection("連接字串");
SqlConnection.open();new SqlCommand();
SqlCommand.commandtext = " ";new SqlDataReader();
Sqlcommand.connection = " ";
while(sqlDataReader.read())SqlDataReader.close();
{}
SqlConnection.close();
==================================
How to update a specific table ?
using System.Data.SqlClient;
sqlconnection conn = new sqlconnection() ;
conn.open();
sqlcommand cmd = new sqlcommand() ;cmd.connection = conn ;
cmd.commandtext = " Update table_name SET item = 'value' where item = 'value' " ;
cmd.ExecuteNonQuery() ; //done
====================================
how to insert a new row into datagridview by yourself
datagridview_name.rows.add(string,string,string,string) *參數的數目跟你設定欄位數目有關
how to insert a new row into the Table
sqlconnection conn_insert = new sqlconnection();conn_insert.open();
sqlcommand cmd_insert = new sqlcommand();
cmd_insert.commandtext = " Insert into table_name (xx,xx,xx) values ('yy','yy','yy') " ;
cmd_insert.connection = conn_insert ;
cmd.insert.ExecuteNonQuery() ;
conn_insert.closer() ; //done
沒有留言:
張貼留言