在vs2010中用C#实现对SQL数据库中的表的查询、添加、修改、删除数据,具体代码怎么写?

2024-11-23 23:53:56
推荐回答(4个)
回答1:

我给你写一个例子吧,其他功能依次改改就可以实现的:
///


/// 获取数据库连接
///

///
public static SqlConnection GetConnection()
{
string connStr = @"Data Source=WIN-20120404HSE;Initial Catalog=BooksManage;Integrated Security=True";
return new SqlConnection(connStr);
}
//这是增加一天图书信息(你自己建一张表,然后这张表的字段就是你上面列出来的,然后你根据你的表把我写的这个sql语句换成你的就ok了,你先做,如果不懂的话,在追问。)
public void AddTbook(Tbook tbook)
{

string sql = string.Format("insert into Tbook values('{0}','{1}','{2}','{3}','{4}',@bookCover,'{5}','{6}','{7}','{8}') ",
tbook.BookName, tbook.BookTypeId, tbook.BookAuthor, tbook.BookPrice, tbook.BookContent, tbook.BookCode, tbook.BookInLib,tbook.BookPublishTime,tbook.BookPublisher);
SqlConnection conn = null;
try
{
conn = ConnectionManager.GetConnection();
conn.Open();
//获取SqlCommand,封装sql
SqlCommand command = new SqlCommand(sql, conn);
SqlParameter prm = new SqlParameter("@bookCover", SqlDbType.VarBinary, tbook.BookCover.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, tbook.BookCover);
command.Parameters.Add(prm);
//发送SQL
command.ExecuteNonQuery();
}
catch (SqlException)
{
throw new DAOException();
}
finally
{
if (conn != null)
{
conn.Close();
}
}

}

回答2:

//1.声明数据库连接字符串
string strcon = "data source=.;initial catalog=itdb;uid=sa;pwd=sun@0918";
//2.创建数据库连接对象
SqlConnection con = new SqlConnection(strcon);
//3.打开数据库连接
con.Open();
//4.编写SQL语句
string sql = "delete from phzw where name='" + id+"'";
SqlCommand cmd = new SqlCommand(sql, con);
//6.选择Command的适合方法
int res = cmd.ExecuteNonQuery();
if (res > 0)
{
MessageBox.Show("删除成功");
this.BindData();
}
else
{
MessageBox.Show("删除失败");
}
//7.关闭数据库连接
con.Close();

这是删除的初级代码,新增和修改,只需修改SQL语句就可以了

回答3:

//1.声明数据库连接字符串
string strcon = "data source=.;initial catalog=itdb;uid=sa;pwd=sun@0918";
//2.创建数据库连接对象
SqlConnection con = new SqlConnection(strcon);
//3.打开数据库连接
con.Open();
//4.编写SQL语句
string sql = "delete from phzw where name='" + id+"'";
SqlCommand cmd = new SqlCommand(sql, con);
//6.选择Command的适合方法
int res = cmd.ExecuteNonQuery();
if (res > 0)
{
MessageBox.Show("删除成功");
this.BindData();
}
else
{
MessageBox.Show("删除失败");
}
//7.关闭数据库连接
con.Close();

这是删除的初级代码,新增和修改,只需修改SQL语句就可以了

回答4:

网上搜个SQLHelper