一、在App.config配置文件中,配置连接字符串
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="dbConnStr" connectionString="Data Source=.; Initial Catalog=MyTest;User ID=sa;Password=123456"/>
</connectionStrings>
</configuration>
二、SqlHelper类,封装对数据库操作的代码
class SqlHelper
{
//读取配置文件中的连接字符串
private static string connStr = ConfigurationManager.ConnectionStrings["dbConnStr"].ConnectionString;
public static int ExecuteNonQuery(string sql,params SqlParameter[] parameters)
{
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(parameters);
return cmd.ExecuteNonQuery();
}
}
}
public static object ExecuteScalar(string sql, params SqlParameter[] parameters)
{
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(parameters);
return cmd.ExecuteScalar();
}
}
}
//只用来执行查询结果比较少的sql
public static DataTable ExecuteDataTable(string sql, params SqlParameter[] parameters)
{
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(parameters);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
return dataset.Tables[0];
}
}
}
}
三、测试代码
SqlHelper.ExecuteNonQuery("insert into T_Student(Name,Age) values('a',33)");
DataTable table = SqlHelper.ExecuteDataTable("select * from T_Student where Age=@Age or Name=@Name",
new SqlParameter("@Age", 50),new SqlParameter("@Name","yzk"));
foreach (DataRow row in table.Rows)
{
string name = (string)row["Name"];
MessageBox.Show(name);
}