C#数据库编程例子{
namespace WindowsApplication1
public partial class Form1 : Form {
private SqlConnection tempConnection = new SqlConnection(\id=localhost;database=tempdb;Connect Timeout=30;Trusted_Connection=yes\); private SqlDataAdapter da;
private DataTable tblDataSource = new DataTable(); private string strSQL = \; SqlConnection conn; SqlCommand da1; public Form1() {
InitializeComponent(); }
private void button1_Click(object sender, EventArgs e) {
this.strSQL = \;
this.da = new SqlDataAdapter(this.strSQL, this.tempConnection); tblDataSource.Clear(); this.da.Fill(tblDataSource);
this.dataGridView1.DataSource = tblDataSource; }
private void button2_Click(object sender, EventArgs e) {
string txt1 = \Security=SSPI;database=tempdb;\; string txt2 =
\; txt2 += textBox1.Text + \; txt2 += textBox2.Text + \;
txt2 += textBox3.Text + \;//最后结果要保证在TextBox中输入的内容被单引号括住 conn = new SqlConnection(txt1); conn.Open();//打开数据库连接 da1 = new SqlCommand(txt2, conn); da1.ExecuteNonQuery();//执行SQL语句 //textBox1.Text = \ //textBox2.Text = \ //textBox3.Text = \
conn.Close();//关闭数据库连接 MessageBox.Show(\插入数据成功!\); }
private void button3_Click(object sender, EventArgs e) {
string txt1 = \Security=SSPI;database=tempdb;\;
StringBuilder strSql = new StringBuilder(); strSql.Append(\);
strSql.Append(\ + textBox2.Text.Trim() + \); strSql.Append(\ + textBox3.Text.Trim() + \); strSql.Append(\ + textBox1.Text.Trim() + \); string st2 = strSql.ToString(); MessageBox.Show(st2);
conn = new SqlConnection(txt1); conn.Open();//打开数据库连接 da1 = new SqlCommand(st2, conn); da1.ExecuteNonQuery();//执行SQL语句 textBox1.Text = \; textBox2.Text = \; textBox3.Text = \;
conn.Close();//关闭数据库连接 MessageBox.Show(\插入数据成功!\); }
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) {
DataGridViewRow myrow = dataGridView1.SelectedRows[0]; textBox1.Text = myrow.Cells[\].Value.ToString(); textBox2.Text = myrow.Cells[\].Value.ToString(); textBox3.Text = myrow.Cells[\].Value.ToString(); }
private void Form1_Load(object sender, EventArgs e) {
this.strSQL = \;
this.da = new SqlDataAdapter(this.strSQL, this.tempConnection); this.da.Fill(tblDataSource);
this.dataGridView1.DataSource = tblDataSource; DataGridViewRow myrow = dataGridView1.SelectedRows[0]; textBox1.Text = myrow.Cells[\].Value.ToString(); textBox2.Text = myrow.Cells[\].Value.ToString(); textBox3.Text = myrow.Cells[\].Value.ToString(); } }