数据库操作
Posted ww123
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据库操作相关的知识,希望对你有一定的参考价值。
string strcon = @"Data Source=.;Initial Catalog=XSXX;Integrated Security=True";
//Data Source=数据库 Initial Catalog=目录
添加操作:
using (SqlConnection con=new SqlConnection(strcon)) //连接数据库 { string sql = "INSERT INTO XS VALUES(‘" + user + "‘,‘" + pwd + "‘)"; //数据库指令 XS:表名称
//INSERT INTO XS VALUES(‘张山‘,‘123456‘);
using (SqlCommand cmd=new SqlCommand(sql,con)) { con.Open(); //打开数据库 cmd.ExecuteNonQuery();//执行命令 } }
删除操作:
int r = dataGridView1.SelectedRows.Count; //要删除的行数
if (r != 0) { int index = dataGridView1.CurrentRow.Index; //获取该行的位置 string s = dataGridView1.Rows[index].Cells[0].Value.ToString(); //第一个字段的内容 using (SqlConnection con = new SqlConnection(strcon)) { string sql = "delete from " + Table + " where 账号=‘" + s + "‘";
//delete from XS where name=‘张三‘ 删除指令 using (SqlCommand cmd = new SqlCommand(sql, con)) { con.Open(); cmd.ExecuteNonQuery(); } } }
修改:
using (SqlConnection con = new SqlConnection(strcon)) { string sql = "update " + Taable + " set 密码=‘" + s + "‘ where 账号=‘" + user + "‘"; // update XS set 密码=‘654321‘ where 账号=‘张三‘ using (SqlCommand cmd = new SqlCommand(sql, con)) { con.Open(); cmd.ExecuteNonQuery(); } }
查询:
using (SqlConnection sqlcon = new SqlConnection(strcon)) { sqlcon.Open(); string sql = "SELECT * FROM " + Taable + " where 账号=‘" + content + "‘";
//SELECT * FROM XS where 账号=‘张三‘; SqlCommand cmd = new SqlCommand(sql, sqlcon); SqlDataAdapter myda = new SqlDataAdapter(cmd); myst.Tables.Clear(); //Dataset myst=new Dataset(); myda.Fill(myst, "" + Taable + ""); dataGridView1.DataSource = myst.Tables["" + Taable + ""]; }
以上是关于数据库操作的主要内容,如果未能解决你的问题,请参考以下文章