2. C# 连接数据库
  C# 连接数据库的思路是:
  1)连接给定参数建立连接对象; 2)利用连接对象建立SQL语句对象; 3)利用SQL语句对象执行并处理数据。
  如连接SQL Server:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//connection-string(Local Server:127.0.0.1) & SQL-string define
string conString = "Server=(local); database=test; uid=sa; password=123456";
string sqlString = "select * from Monitor;";
//create a connection
SqlConnection con = new SqlConnection(conString);
con.Open();
//create a SQL command within connection, use SqlDataReader(light-level) to read retrieved data
SqlCommand cmd = new SqlCommand(sqlString, con);
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
Console.WriteLine("{0} {1} {2} {3}", sdr["ID"],sdr["RecordTime"],sdr["VideoView"],sdr["Fluency"]);
con.Close();
cmd.Dispose();
//create a SQL command within connection, use SqlDataAdapter to read retrieved data
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqlString, con);
DataSet dst = new DataSet();
sda.Fill(dst, "Monitor");
foreach (DataRow row in dst.Tables["Monitor"].Rows)
Console.WriteLine(row["ID"] + " " + row["RecordTime"] + " " + row["VideoView"] + " " + row["Fluency"]);
con.Close();
Console.ReadKey();
}
}
}
  其中连接字串中Server是数据库server的ip地址,database是指定连接的数据库。后分别以SqlDataReader和SqlDataAdapter的方式处理了数据。
  以上看来,连接数据库的时候,你得告诉程序:1)我去连接哪个数据库server呀,2)我连到server了,我去连哪个数据库呀?不然我的sql语句找不到table么。