string sqlcon="Data Source=.;Initial Calalog=MySchool;User ID=sa;Pwd=.";
Connection:打开数据库连接
程序与数据库沟通的桥梁
SqlConnection con=new SqlConnection(sqlcon);
try
{
//可能发生异常的代码
con.Open();
}
catch(Exception ex)
{
//捕获异常
Console.WriteLine(ex);
}
finally
{
con.Close();
//永远都会被执行
}
Command:向数据库发送命令,提交SQL命令并从数据源中返回结果
string sql="select count(*) from Student where StudentNo='"+username+"' and LoginPwd='"+password+"'";
//向数据库发送一条SQL语句
SqlCommand command=new SqlCommand(sql,con);
//结果
int count=(int)command.ExecuteScalar();
if(count>0)
{
Console.WriteLine("登录成功");
}else
{
Console.WriteLine("查无此人");
}
class Test { string sql = "Data source = .;Initial Catalog = TestAll;User ID =Sa;PassWord=asiga0."; public void Show() { do { Console.WriteLine("****************"); Console.WriteLine(" 欢迎使用金牌查询系统 "); Console.WriteLine("****************"); Console.WriteLine("1.省市金牌数 2.金牌总数"); Console.WriteLine("请选择"); int choose = int.Parse(Console.ReadLine()); switch (choose) { case 1: Console.WriteLine(dan()); Console.WriteLine("是否继续查询"); string y = Console.ReadLine(); if (y.ToLower().Trim().Equals("y")) { continue; } break; case 2: Console.WriteLine(zong()); Console.WriteLine("是否继续查询"); string k = Console.ReadLine(); if(k.ToLower().Trim().Equals("y")){ continue; } break; } break; } while (true); } public int dan() { SqlConnection conn = new SqlConnection(sql); try { Console.WriteLine("请输入省市名称"); string pr = Console.ReadLine(); conn.Open(); string s = string.Format("select number from GoldMedal where Province ='{0}'", pr); SqlCommand comm = new SqlCommand(s, conn); int a = (int)comm.ExecuteScalar(); return a; } catch (Exception ex) { Console.WriteLine(ex.Message); return -1; throw; } finally { conn.Close(); } } public int zong() { SqlConnection conn = new SqlConnection(sql); try { conn.Open(); string s = "select sum(number) from GoldMedal "; SqlCommand comm = new SqlCommand(s, conn); int a = (int)comm.ExecuteScalar(); return a; } catch (Exception ex) { Console.WriteLine(ex.Message); return -1; throw; } finally { conn.Close(); } } }