C#怎么实现对SQL数据库增删改查

明天就要考试了 , 有些地方还不是很明白 .

考试估计你也没时间写DBHelper类了,
我简单描述一下,也有代码供你参考
//拼写SQL语句增加
string strSql = "insert 表名 (列名,列名,列名,列名)"
+" values ('{0}',{1},'{2}','{3}')";

strSql = string.Format(strSql, 文本框插入值,文本框插入值, 文本框插入值, 文本框插入值);

try
{
//创建 Command 对象
SqlCommand comm = new SqlCommand(strSql, conn);

//打开连接
conn.Open();

//执行命令
int iResult = comm.ExecuteNonQuery();

if (iResult != 1)
{
MessageBox.Show("添加失败!");
}
else
{
MessageBox.Show("添加成功!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2013-08-01
public class DBHelper
{
public static string GetString()
{
return System.Configuration.ConfigurationSettings.AppSettings["Conection"];
}
public static SqlConnection GetSqlConnection()
{
return new SqlConnection(GetString());
}
public static SqlCommand GetSqlCommand(string sql)
{
SqlConnection conn = GetSqlConnection();
conn.Open();
return new SqlCommand(conn, sql);
}
public static void IsClose()
{
SqlConnection con = new SqlConnection();
if(con.State==ConnectionState.Open)
{
con.Close();
}
}
}

编写好上面的数据库操作类后,在对数据库操作的时候只要NEW出该类的对象,调用其SqlCommand(SQL语句)中的各种增删改方法就可以,接收他们的返回值就可以了。
第2个回答  2013-08-01
C# 3.5新增LINQ ,用它你就好比是操作一个集合一样,不必要自己去做什么转接.
相似回答
大家正在搜