C#与SQL Server数据库连接
时间:2021-07-01 10:21:17
帮助过:39人阅读
System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace Demp13
{
class Program
{
static void Main(
string[] args)
{
//1.创建连接字符串
string str =
"server=.;database=MySchool;uid=sa;pwd=密码";
// string str = "Data Source=.;Initial Catalog=MySchool;User ID=sa;Password=accp";
//2.创建connection对象
SqlConnection conn =
new SqlConnection(str);
try
{
//3.打开链接
conn.Open();
Console.WriteLine("打开链接成功");
//4.准备sql语句,创建command对象,并执行sql语句
Console.WriteLine(
"请输入用户名");
string name =
Console.ReadLine();
Console.WriteLine("请输入密码");
string pwd =
Console.ReadLine();
string sql =
"select COUNT(*) from admin where loginId=‘"+name+
"‘ and loginPwd=‘"+pwd+
"‘";
SqlCommand cmd =
new SqlCommand(sql,conn);
//5.执行sql语句,得到返回结果
int r=
Convert.ToInt32(cmd.ExecuteScalar());
if (r >
0)
{
Console.WriteLine("登陆成功");
}
else {
Console.WriteLine("登陆失败");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally {
//4.关闭链接
conn.Close();
Console.WriteLine("关闭链接成功");
}
}
}
}
C#与SQL Server数据库连接
标签:except 创建 admin .text exception server bsp ESS OLE