using System.Data; //表的命名空间
using System.Data.SqlClient; //sql相关的命名空间
Console.WriteLine("请输入一个学号:");
//创建连接
//还有方法二
SqlConnection conn = new SqlConnection("Server=DESKTOP-52JB620;DataBase=stu_db;Trusted_Connection=SSPI");
//有密码的
//SqlConnection conn = new SqlConnection("Server=DESKTOP-52JB620;DataBase=stu_db;uid=xx;pwd=xx");
//打开连接
//判断是否已有连接
if(conn.State == ConnectionState.Closed)
conn.Open();
//创建SQL
string stu_no = Console.ReadLine();
//字符串拼接 string +
string sql = "SELECT * FROM stu_inf WHERE ID = '"+stu_no+"'";
SqlCommand comm = new SqlCommand(sql, conn);//参数1:sql语句字符串。参数2:已经打开的数据库连接对象
//执行commend对象
//接受查询到的SQL结果
//comm.Connection = conn;
SqlDataReader rd=null;
try {
rd = comm.ExecuteReader();
while (rd.Read())
{
Console.Write(rd["NAME"].ToString());
Console.Write(rd["GENDER"].ToString());
Console.Write(rd["AGE"].ToString());
Console.WriteLine();
}
}
catch(Exception ex) {
Console.WriteLine(ex.Message); //咋不抛异常呢
}
finally
{
conn.Close();
}
//Console.WriteLine(sql);
Console.ReadLine();