读书人

Visual C# 中怎么写SQL语句进行有条件

发布时间: 2012-02-13 17:20:26 作者: rapoo

Visual C# 中如何写SQL语句进行有条件的查询?
代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace SQLSearch
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{


}

private void button1_Click(object sender, EventArgs e)
{
//查询tby07中所有信息
this.tby07TableAdapter.Fill(this.chisbzDataSet.tby07);
}

private void button3_Click(object sender, EventArgs e)
{
this.Close();
}

private void button2_Click(object sender, EventArgs e)
{
string sql; //查询符合输入条件的信息
sql = "select * from tby07 where dmmc= ' "+textBox1.Text+ " ' ";

/////接下来如何写 才能在dataGridView1中显示查询结果?
}
}
}

各位帮忙补充下…… 谢谢!!!

[解决办法]
接下来 还是用Adapter.Fill(ds);
然后再将dataGridView1的数据源制定到这个ds就ok了
[解决办法]
查询得到结果放到ds(DataSet)中,



dataGridView1.DataSource=ds.tables[0];

..........................
[解决办法]
用DataView.RowFilter吧,更方便一些。
得到一个DataSet为ds
DataView dv = ds.Tables[0].defaultview;
dv.RowFilter = "dmmc like '% " + textBox1.Text.Trim() + "% ' ";
dataGridView1.DataSource = dv;
[解决办法]
简写:
using System.Data.SqlClient;

...
private SqlConnection cn=new SqlConnection( "Data Source=.;Initial Catalog=XXX;User ID=sa;Password= ");
private SqlDataAdapter da;
private DataSet ds=new DataSet();

....
da = new SqlDataAdapter( "sql ", cn);
da.Fill(ds, "tby07 ");
this.dataGridView1.DataSource = ds.Tables[ "tby07 "];

...

[解决办法]
SqlConnection sqlConn = new SqlConnection();
sqlConn.ConnectionString =global::SecConsole.Properties.Settings.Default.emg_nmdbV200;
sqlConn.Open();

string sql;
sql = "select * from tby07 where dmmc= ' "+textBox1.Text+ " '

SqlCommand sqlComm = new SqlCommand(sql,sqlConn);
SqlDataAdapter sqlDapt = new SqlDataAdapter(sqlComm);
DataTable dtSelect = new DataTable();
sqlDapt.Fill(dtSelect);

dataGridView1.DataSource = dtSelect;
[解决办法]
用DataView!
[解决办法]
sqlConn.ConnectionString =global::SecConsole.Properties.Settings.Default.emg_nmdbV200;
这句改为
sqlConn.ConnectionString = "server=localhost;uid=sa;pwd = sa;database=pubs ";
uid是进入数据库的用户名,pwd是密码.database是具体数据库的名字

读书人网 >C#

热点推荐