Console.WriteLine("请输入要查询的代号");
string code = Console.ReadLine();
SqlConnection conn = new SqlConnection("server=.;database=mydb;uid=sa;pwd=123");
SqlCommand cmd = conn.CreateCommand();
try
{
//局部变量传参数,防止字符串注入攻击
cmd.CommandText = "select * from Test where Code =@code";
cmd.Parameters.AddWithValue("@code", code);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Console.WriteLine("{0} {1}", dr[0], dr[1]);
}
}
catch (Exception)
{
throw;
}
finally
{
conn.Close();
}