一、填写配置文件App.config
<connectionStrings>
<add name="SMTDB" connectionString="Server=192.168.1.23;Initial Catalog=Smes;User ID=root;Password=123" providerName="System.Data.SqlClient" />
</connectionStrings>
使用 name = “SMTDB” 使用配置文件 创建ControllerSQL文件编写 SQL语句
BasicTool bt = new BasicTool();
public DataTable Select_struct(string number) {
DataTable data = new DataTable();
try {
string sql = "Select * from school ";
data = bt.ExcuteQuery(sql);
}
catch (Exception e) {
MessageBox.Show(e.Message);
}
return data;
}
创建 BasicTool.cs文件链接数据库
public DataTable ExcuteQuery(string sql)
{
DataTable dt = new DataTable();
//链接数据库
SqlConnection conn = GetConn();
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}
public SqlConnection GetConn()
{
string connectionString =
ConfigurationManager.ConnectionStrings["SMTDB"].ToString();
SqlConnection conn = new SqlConnection(connectionString);
return conn;
}
二、C#保存表格内容,快速同步
DataTable dt 表格内修改数据 ,sql 查询语句
public void Excutetest(DataTable dt, string sql) {
SqlConnection conn = GetConn();
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
SqlCommandBuilder scb = new SqlCommandBuilder(adapter);
if (dt.GetChanges()!=null) {
adapter.Update(dt.GetChanges());
dt.AcceptChanges();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}
public void Updata_Master(DataTable dt) {
string sql = "select top 0 partIndex,partNumber,partName,createTime,lastTime,partDesc,PackingCounter,PackingControlLevel,CustomerNO,QtyLable from partMaster";
bt.Excutetest(dt, sql);
}
三、其它使用方法
//执行sql语句
public int Excutesql(string sql)
{
SqlConnection conn = GetConn();
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
int count = cmd.ExecuteNonQuery();
return count;
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}