1. using System.Data.SqlClient; 要加入這行喔!!
2. 資料庫連接範例 INSERT, UPDATE, DELETE 語法(此範例使用的是INSERT)
程式碼:
private void DBSelectUpdateDelect()
{
//要連接資料庫所需要的 SqlConnection 物件
sqlConnection dataConnection = new SqlConnection();
//要連接資料庫的位置
//Initial Catalog = ArrangeSubjectDB 這是欲連接的資料庫
//server = (Local) server的位置
String sqlConnectionStr = "Persist Security Info=False;Integrated Security=true;Initial
Catalog=ArrangeSubjectDB;server=(Local)";
//SQL INSERT 語法
// INSERT INTO [table] ([欄位名1],[欄位名2],[欄位名3],....) VALUES (@值1, @值2, @值3,...)
string strMsgInsert = @"INSERT INTO Arrangement
([teachID],[CS_ID],[classDate],[classSession],[classStartTime],[classEndTime])
VALUES(@value1, @value2, @value3,@value4, @value5, @value6) ";
//C# SQL Command 物件 SqlCommand( SQL語法 , SqlConnection )
SqlCommand mySqlCmd = new SqlCommand(strMsgInsert , dataConnection);
//SQL UPDATE 語法
// UPDATE [table] [欄位名2] = @值1 , [欄位名3] = @值2, [欄位名4] = @值3,....)
WHERE [欄位名1] = @值4
string strMsgUpdate = @"UPDATE Arrangement
SET CS_ID = @value2, classDate = @value3,
classSession = @value4, classStartTime = @value5, classEndTime = @value6
WHERE teachID = @value1 ";
//C# SQL Command 物件 SqlCommand( SQL語法 , SqlConnection )
//SqlCommand mySqlCmd = new SqlCommand(strMsgUpdate , dataConnection);
//SQL DELETE 語法
// DELETE FROM [table]
WHERE [欄位名] = @值1
string strMsgDelete = @"DELETE Arrangement
WHERE teachID = @value1 ";
//C# SQL Command 物件 SqlCommand( SQL語法 , SqlConnection )
//SqlCommand mySqlCmd = new SqlCommand(strMsgDelete , dataConnection);
//try catch
try
{
//設置資料庫位置
dataConnection.ConnectionString = sqlConnectionStr;
//連接資料庫
dataConnection.Open();
//塞C#參數到SQL語法中的參數
mySqlCmd.Parameters.AddWithValue("@value1", teachID);
mySqlCmd.Parameters.AddWithValue("@value2", CS_ID);
mySqlCmd.Parameters.AddWithValue("@value3", classDate);
mySqlCmd.Parameters.AddWithValue("@value4", classSession);
mySqlCmd.Parameters.AddWithValue("@value5", classStartTime);
mySqlCmd.Parameters.AddWithValue("@value6", classEndTime);
//執行SQL INSERT 語法
mySqlCmd.ExecuteNonQuery();
//關閉資料庫
dataConnection.Close();
}
catch (Exception e)
{
//抓錯誤訊息
MessageBox.Show(e.Message, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
finally
{
//清除
mySqlCmd.Cancel();
dataConnection.Close();
dataConnection.Dispose();
}
}
.
.
sql = "SELECT....FROM... where ID=@ID AND name LIKE @name + '%' "
或
sql = "SELECT....FROM... where ID=@ID AND name LIKE '%' + @name + '%' "
沒有留言:
張貼留言