C#連線SQLServer資料庫
阿新 • • 發佈:2018-12-06
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); } }