C#连接SQL数据库
中国制造交易网
连接数据库的步骤:
1、建立SqlConnection对象;
2、指定SqlConnection对象的ConnectionString 属性;
3、打开数据库连接;
4、指定SQL语句;
5、建立SqlDataAdapter对象和DataSet对象(myDataAdapter = new SqlDataAdapter(strCmd,conn);
);
6、添冲DataSet;
7、给DataGrid指定数据源
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "data source = (local);initial catalog = test; user id = sa;password = sa";
conn.Open();
string strCmd;
strCmd = "select * from test";
SqlDataAdapter myDataAdapter;
DataSet myDataSet = new DataSet();
myDataAdapter = new SqlDataAdapter(strCmd,conn);
myDataAdapter.Fill(myDataSet,"test");
myTestDataGrid.DataSource = myDataSet.Tables["test"];
说明: 数据库安装在本地(local);数据库名称为test;用户名为sa;密码为sa;
数据库中的表为test;
连接数据库的步骤:
1、建立SqlConnection对象;
2、指定SqlConnection对象的ConnectionString 属性;
3、打开数据库连接;
4、指定SQL语句;
5、建立SqlDataAdapter对象和DataSet对象(myDataAdapter = new SqlDataAdapter(strCmd,conn);
);
6、添冲DataSet;
7、给DataGrid指定数据源
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "data source = (local);initial catalog = test; user id = sa;password = sa";
conn.Open();
string strCmd;
strCmd = "select * from test";
SqlDataAdapter myDataAdapter;
DataSet myDataSet = new DataSet();
myDataAdapter = new SqlDataAdapter(strCmd,conn);
myDataAdapter.Fill(myDataSet,"test");
myTestDataGrid.DataSource = myDataSet.Tables["test"];
说明: 数据库安装在本地(local);数据库名称为test;用户名为sa;密码为sa;
数据库中的表为test;