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); } }