C#数据库编程例子
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
C#数据库编程例子
namespace WindowsApplication1
{
public partial class Form1 : Form
{
private SqlConnection tempConnection = new SqlConnection("workstation
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 = "select * from student";
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 = "workstation id=localhost;Integrated
Security=SSPI;database=tempdb;";
string txt2 =
"Insert Into Student(xh,xm,xb) Values('";
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 = "workstation id=localhost;Integrated
Security=SSPI;database=tempdb;";
StringBuilder strSql = new StringBuilder();
strSql.Append("update Student set ");
strSql.Append("xm='" + textBox2.Text.Trim() + "',");
strSql.Append("xb='" + textBox3.Text.Trim() + "'");
strSql.Append(" where xh='" + 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["xh"].Value.ToString();
textBox2.Text = myrow.Cells["xm"].Value.ToString();
textBox3.Text = myrow.Cells["xb"].Value.ToString();
}
private void Form1_Load(object sender, EventArgs e)
{
this.strSQL = "select * from student";
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["xh"].Value.ToString();
textBox2.Text = myrow.Cells["xm"].Value.ToString();
textBox3.Text = myrow.Cells["xb"].Value.ToString();
}
}
}。