带参的sql语句
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 带参数的sql语句
{
class Program
{
static void Main(string[] args)
{
string constr = “Server=localhost;Database=user;user=root;password=liuyang;”;
while (true)
{
Console.WriteLine(“请输入名称:”);
string u = Console.ReadLine();
Console.WriteLine(“请输入密码:”);
string p = Console.ReadLine();
using (SqlConnection conn = new SqlConnection(constr))
{
//带参数的sql语句 @后代表参数名
string sql = "select id from users where username=@username and password=@password";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
//声明变量,与sql语句中的参数绑定
//SqlParameter username = new SqlParameter("@username", System.Data.SqlDbType.VarChar, 50) { Value = u };
//SqlParameter password = new SqlParameter("@password", System.Data.SqlDbType.VarChar, 50) { Value = p };
//将变量添加到SqlCommand变量中
//cmd.Parameters.Add(username);
//cmd.Parameters.Add(password);
SqlParameter[] sq = new SqlParameter[] { new SqlParameter("@username", System.Data.SqlDbType.VarChar, 50) { Value = u }, new SqlParameter("@password", System.Data.SqlDbType.VarChar, 50) { Value = p } };
cmd.Parameters.AddRange(sq);
if (cmd.ExecuteScalar() != null)
{
//查询一个数据,使用cmd.ExecuteScalar()
int id = (int)cmd.ExecuteScalar();
Console.WriteLine(id);
}
}
}
}
}
}
以上是 带参的sql语句 的全部内容, 来源链接: utcz.com/z/532667.html