一.使用包 using System.Data.SqlClient;
没有包,使用NuGet包管理器下载
二.连接数据库
1.SQL sever 身份验证
Data Source 指定数据源(ip)
Initial Catalog 数据库名
User Id 账号
Password 密码
string connstring = "Data Source=.;Initial Catalog=AirTicket;UserId=lyc;Password=123456";
2. windows身份验证
Data Source 指定数据源(ip)
Initial Catalog 数据库名
Integrated Security=True/SSPI
string connstring = "Data Source=.;Initial Catalog=AirTicket;Integrated Security=True";
三,连接对象
//创建连接对象
SqlConnection conn = new SqlConnection(connstring);
//设置命令对象
SqlCommand cmd = conn.CreateCommand();
//打开数据连接
conn.Open();
四、插入.删除.更新.查询
1.插入数据
cmd.CommandText = "inset into AirCompany values('衡阳航空','衡阳市南岳','95538'";
//执行命令
cmd.ExecuteNonQuery();
2,删除数据
cmd.CommandText = "delete AirCompany where hotLine='A'";
//执行命令
cmd.ExecuteNonQuery();
3.更新数据
cmd.CommandText = "update AirCompany set hotLine='95539' where companyName='职院航空'";
//执行命令
cmd.ExecuteNonQuery();
4.查询数据
// 定义操作的SQL语句
cmd.CommandText = "Select ClassID from tbClass where ClassName='网页设计'";
// 获取查询结果
SqlDataReader reader = cmd.ExecuteReader();
//解析查询结果
while (reader.Read())
{
if (reader.HasRows)
{
int id = reader.GetInt32(0);
string name = reader.GetString(1);
Console.WriteLine(reader.GetInt32(0) + ":" + reader.GetString(1) + ":" + reader.GetString(2));
}
}
五、关闭数据连接
conn.Close();