C#在VisualStudio中操作SQL資料庫檔案
阿新 • • 發佈:2018-12-30
1. 要在專案中新增一個基於服務的資料庫或本地資料庫檔案;
2. 在程式碼執行開始先執行如下程式碼,否則資料庫表中看不到執行的語句
string dataDir = AppDomain.CurrentDomain.BaseDirectory; if(dataDir.EndsWith(@"\bin\Debug\") || dataDir.EndsWith(@"\bin\Release\")) { dataDir = System.IO.Directory.GetParent(dataDir).Parent.Parent.FullName; AppDomain.CurrentDomain.SetData("DataDirectory", dataDir); }
3. 定義連線字串:@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"
4. 編寫程式:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; namespace 資料庫1 { class Program { static void Main(string[] args) { string dataDir = AppDomain.CurrentDomain.BaseDirectory; if(dataDir.EndsWith(@"\bin\Debug\") || dataDir.EndsWith(@"\bin\Release\")) { dataDir = System.IO.Directory.GetParent(dataDir).Parent.Parent.FullName; AppDomain.CurrentDomain.SetData("DataDirectory", dataDir); } string
[email protected]"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"; using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { string username = Convert.ToString(System.DateTime.Now.Millisecond); cmd.CommandText = "insert into t_user (username,password) values ('" + username + "', '3333')"; cmd.ExecuteNonQuery(); Console.WriteLine("執行成功"); cmd.CommandText = "select * from t_user where username='" + username + "'"; using (SqlDataReader reader = cmd.ExecuteReader()) { if (reader.Read()) { string password = reader.GetString(reader.GetOrdinal("password")); Console.WriteLine("使用者: " + username + ", 密碼: " + password); } else { Console.WriteLine("沒有這個使用者 " + username); } } } } Console.ReadKey(); } } }