1.using System.Data.Sqlclient;
using System.Configuration;
2.建立连接字符串,可以写一个数据库配置文件,app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings >
<add key="ConnStr" value="Data Source=**;Initial Catalog=数据库;Integrated Security=True" />
</appSettings>
</configuration>
3.主要代码:
string connStr = ConfigurationSettings.AppSettings["ConnStr"];
SqlConnection sqlcn=new SqlConnection();
sqlcn.ConnectionString=connStr;
sqlcn.Open();
SqlCommand sqlcmd=new SqlCommand();
sqlcmd.CommandText ="select * from A";
sqlcmd.Connection=sqlcn;
SqlDataAdapter sqlda=new SqlDataAdapter(sqlcmd.CommandText,sqlcn);
DataSet ds = new DataSet();
sqlda.Fill(ds);
sqlcn.Close();
//操作数据集
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
DataRow dr = ds.Tables[0].Rows[i];
if (TextBox1.Text = dr[0].ToString())
{
TextBox2.Text = dr[1].ToString();
}
}