SQL连接VS
实现链接语句
基本方法
Command对象的获取
格式
sqlcommand 命令对象 = new sqlcommand(sql语句,连接对象)
代码例子
//连接字符串的获取
string conn_format = "Data Source=.;Initial Catalog=text;Integrated Security=True";
string conn_str = string.Format(conn_format, "xbd040908");
Console.WriteLine(conn_str);
//获取连接字符串对象
SqlConnection conn = new SqlConnection(conn_str);
Console.WriteLine("连接对象成功:"+conn);
//打开连接对象
conn.Open();
Console.WriteLine("连接已经打开");
//获得sql语句
string sql = "select * from zhanguo;";
SqlCommand cmd = new SqlCommand(sql,conn);
Console.WriteLine("获取cmd对象成功");
Console.WriteLine(cmd);
执行sql语句
Console.WriteLine(cmd.ExecuteScalar());
//关闭连接对象
conn.Close();
Console.WriteLine("连接已经关闭");
Console.ReadKey();
- 查询内容
命令对象
对象的方法
命令对象.ExecuteReader()
读的方法
对象.Read()
功能:读取下一行
代码例子
//捕获一个数据朗读者
SqlDataReader reader = cmd.ExecuteReader();
//查询朗读者数据
reader.Read();
Console.WriteLine(reader["name"]);
Console.WriteLine(reader["zl"]);
//查询下一行数据
reader.Read();
Console.WriteLine(reader["country"]);
//查询所有数据
Console.WriteLine(reader.Read());
while (reader.Read())
{
Console.WriteLine(reader["name"]);
}