c#访问数据库
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Common;
using System.Data.SqlClient;
//using System.Data.SqlTypes;
namespace database
{
class Program
{
static void Main(string[] args)
{
string source = "server=(local);" + "Integrated Security=true;"+"database=图书借阅";
//连接串,本地windows身份登陆sql,连接数据库图书借阅
string select = "SELECT * FROM book";
//查询语句
SqlConnection conn = new SqlConnection(source);
//连接对象
SqlCommand cmd = new SqlCommand(select, conn);
//Sql命令
conn.Open();
//--------读取数据-------------
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("{0} {1} {2} {3} {4} {5}", reader[0].ToString().Trim(), reader[1].ToString().Trim(), reader[2].ToString().Trim(), reader[3].ToString().Trim(), reader[4].ToString().Trim(), reader[5].ToString().Trim());
}
//--------.Trim()方法用于去掉字符串两边的空格
conn.Close(); //☆
//---------返回记录个数---------------------
string select2 = "SELECT COUNT(*) FROM book";
SqlCommand cmd2 =new SqlCommand(select2, conn);
//由此行可见conn对象还没有被撤消
conn.Open();
object o = cmd2.ExecuteScalar();
Console.WriteLine(o.ToString());
conn.Close();
conn.Dispose();
conn = null;
//执行以上两行后conn对象才被撤消。
//此外,.open()和.close()之间,的代码越少,越节省资源。
}
}
}
//图书借阅数据库中有表book, book表有6个属性列