using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using System.Data.Sql; using System.Data.SqlClient;
//這個是連接數據庫用的類
namespace SQLConnectWindows { class sqlhelper { //數據庫名稱 public string sourceName = "UQVYNFZSKG81DQB"; //用戶名稱 public string userName = "sa"; //用戶密碼 public string pwd = "123456"; //連接的數據庫名稱 public string database = "zd_tcTwo"; //連接數據庫 SqlConnection conn; //執行操作 DataSet dataSet = new DataSet(); public DataSet MySQLConnect(string sql) { //連接數據庫 string connstr = "data source=" + sourceName + ";user=" + userName + ";pwd=" + pwd + ";database=" + database; conn = new SqlConnection(connstr); try { //打開數據庫連接 conn.Open(); //執行sql命令 SqlCommand cmd = new SqlCommand(sql, conn); //適配命令通道 SqlDataAdapter adapter = new SqlDataAdapter(cmd); //命令執行 adapter.Fill(dataSet); //清除參數 cmd.Parameters.Clear(); } catch (Exception e) { Console.Write(e.Message); } finally { //關閉數據庫連接 conn.Close(); } return dataSet; } } }
執行SQL語句:在方法中調用
//可以存在於其他類中
private void button1_Click(object sender, EventArgs e) { try { string cmd = "INSERT INTO [dbo].[userInfo]([uid],[uname],[umid])VALUES('" + 1 + "','" + 1 + "','" + 1 + "')"; sqlhelper.MySQLConnect(cmd); } catch (DataException data) { Console.Write(data.Message); } }