一、窗体App.config配置文件的配置
<connectionStrings><add name="con" connectionString="Data Source = WIN-20230216VRB; Initial Catalog = Test01; User ID = sa; Password=jk123" /></connectionStrings>
二、代码
//获取配置文件的链接字符串
string constr = ConfigurationManager.ConnectionStrings["con"].ToString();
//链接数据库
SqlConnection conn = new SqlConnection(constr);
//写防sql注入语句
string sql1 = $"select count(*) from userLOG where username = @name and password =@pwd";
try
{
//判断链接状态是否打开
if (conn.State == ConnectionState.Closed)
conn.Open();
//创建command命令
SqlCommand com = new SqlCommand(sql1, conn);
//利用参数化Parameters.AddWithValue方法添加参数的值分别为name和pwd
com.Parameters.AddWithValue("@name", name);
com.Parameters.AddWithValue("@pwd", pwd);
//返回结果
int result = Convert.ToInt32(com.ExecuteScalar());
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
throw;
}
finally
{
conn.Close();
}