运行到(SqlDataReader reader = cmd.ExecuteReader())时报错

class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入用户名:");
string admin = Console.ReadLine();
Console.WriteLine("请输入密码:");
string password = Console.ReadLine();
using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "slect * Table1 where name='"+admin+"'";
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
string pw = reader.GetString(reader.GetOrdinal("Password"));
if (password == pw)
{
Console.WriteLine("登陆成功!");
}
else
{
Console.WriteLine("密码错误!");
}
}
else
{
Console.WriteLine("用户名不存在!");
}
}
}
}
Console.WriteLine("OK");
Console.ReadKey();
}
}
}
运行到using (SqlDataReader reader = cmd.ExecuteReader())时报语法错误,未处理Sqlexception
请问高手怎么解决,谢谢
我把cmd.ExecuteReader()插到错误语句前面,程序运行到这句的时候就会提前报错,错误与前面一致
把鼠标放在上面的时候下面会显示:
异常
System.Data.SqlClient.SqlException
System.InvalidOperationException
不知道为什么,谢谢

慕后森
浏览 477回答 2
2回答

翻翻过去那场雪

cmd.CommandText = "slect * Table1 where name='"+admin+"'";SQL语句好像写错了,改为:cmd.CommandText = "select * from Table1 where name='"+admin+"'";

aluckdog

多个对象使用using,必须要先声明对象,然后再使用,你现在using外面声明一下要用的对象,试试看
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

SQL Server