步骤
- 引入命名空间
- 创建连接字符串
- 创建连接对象
- 创建sql语句字符串
- 创建命令对象
- 打开连接并执行命令
- 读取数据
- 关闭连接
代码
using System.Data; //表的命名空间
using System.Data.SqlClient; //和SQL相关
namespace 连接字符串
{
class Program
{
static void Main(string[] args)
{
//1创建连接字符串
//方法一
SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder();
scsb.DataSource = "localhost";
scsb.InitialCatalog = "AddressBook";
scsb.IntegratedSecurity = true; //scsb.UserID scsb.Password
//方法二
//string conStr = "Data Source=localhost;Initial Catalog=AddressBook;Integrated Security=True";
//string conStr = "Data Source=localhost;Initial Catalog=AddressBook;User ID=sa;Passwrod=123456";
//2创建连接对象
SqlConnection con = new SqlConnection(scsb.ToString());
//SqlConnection con = new SqlConnection(conStr);
//3创建sql语句
string sql = "select * from TblPerson";
//4创建命令对象
SqlCommand cmd = new SqlCommand(sql, con);
//5打开连接执行命令
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
//6读取数据
while(reader.Read())
{
Console.Write(reader["姓名"].ToString());
Console.Write("\t");
Console.WriteLine(reader[3].ToString());
}
//7关闭连接
con.Close();
Console.ReadKey();
}
}
}