MSSQL一些简单的操作,你修改一下查询条件和传入值就可以用了
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
SqlConnection conn;
SqlCommand cmd;
SqlDataReader rs;
/// <summary>
/// 一般的读取
/// </summary>
public void ReadRS() {
// 连接字符串
string Connstr="Server = (local); Database = EKGStudio; uid = sa;pwd = ECGecg123";
// 实例化连接
SqlConnection conn = new SqlConnection(Connstr);
// 打开连接
conn.Open();
// 查询
cmd = new SqlCommand("select * from Region", conn);
rs = cmd.ExecuteReader();
while(rs.Read()){
Console.WriteLine("ID:{0} 方向:{1}", rs["RegionID"].ToString(), rs[1].ToString());
}
rs.Close();
cmd.Dispose();
conn.Close();
}
/// <summary>
/// 插入记录
/// </summary>
public void Insert() {
try
{
conn = new SqlConnection("server=.;database=Northwind;Integrated Security=SSPI");
conn.Open();
cmd = new SqlCommand("Insert into Region values (5,'中国')", conn);
cmd.ExecuteNonQuery();
Console.WriteLine("插入成功!");
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
finally {
conn.Close();
}
}
/// <summary>
/// 修改记录
/// </summary>
public void Update() {
try
{
conn = new SqlConnection("server=.;database=Northwind;Integrated Security=SSPI");
conn.Open();
cmd = new SqlCommand("Update Region set RegionDescription='china' where RegionID=5", conn);
cmd.ExecuteNonQuery();
Console.WriteLine("修改成功!");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
conn.Close();
}
}
public void Del() {
try
{
conn = new SqlConnection("server=.;database=Northwind;Integrated Security=SSPI");
conn.Open();
cmd = new SqlCommand("Delete Region where RegionID=5", conn);
cmd.ExecuteNonQuery();
Console.WriteLine("删除成功!");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
conn.Close();
}
}
/// <summary>
///
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
Program p = new Program();
p.ReadRS();
//p.Insert();
//p.Update();
//p.Del();
}
}
}
追问我 就是想看看 查询那块的代码 就是 在文本框里输入 一组词之后 按下按钮 可以查出 第三列中 包含这组词的 行 然后 显示在下边的 dataGridView 框里
追答string Connstr="Server = (local); Database = EKGStudio; uid = sa;pwd = ECGecg123";
SqlConnection conn = new SqlConnection(Connstr);
conn.Open();
// 查询字符串
string Selsql="select * from Region"; // 把这里改成你的条件
cmd = new SqlCommand(Selsql, conn);
rs = cmd.ExecuteReader();
while(rs.Read()){
// 读出的数据
// 也可以直接绑定 dataGridView 数据源,查一下MSDN
}
rs.Close();
cmd.Dispose();
conn.Close();
追问如果前边是绑定的数据源 怎么写 我想要 具体到按钮控件的代码
追答在之前可以绑定,查到后你把查到的那一行高亮显示就行了,
GridView1.DataSource 绑定数据源
GridView1.SelectedIndex 选择一行,具体的代码MSDN里面都有的。