C# 链接数据库并查询操作
1、点击视图,点击服务器资源管理
2、点击链接到数据库
3、在出来的界面中点击数据源,点击下图所示
4、选择数据库名等
服务器名在SQL看
这个字符串就是需要建立实例的参数
5、在click事件中可以这样写代码
SqlConnection comn = new SqlConnection("Data Source = JINQI; Initial Catalog = Test; Integrated Security = True"); try { string search = "select * from matnr where(0=0)"; if (this.textBox1.Text.Length>0) { search = search + " and 物料编码=" + "'" + textBox1.Text + "'"; } if (this.textBox2.Text.Length > 0) { search = search + " and 物料描述=" + "'" + textBox2.Text + "'"; } SqlDataAdapter sda = new SqlDataAdapter(search, comn); DataSet ds = new DataSet(); sda.Fill(ds); dataGridView1.DataSource = ds.Tables[0]; dataGridView1.RowHeadersVisible = false; } catch (Exception EX) { MessageBox.Show(EX.Message+EX.StackTrace); }