|
楼主 |
发表于 2014-4-23 14:16:29
|
显示全部楼层
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
namespace 测试对数据库的直接操作
{
public partial class frm_db_op : Form
{
public frm_db_op()
{
InitializeComponent();
}
//#region//对ExecuteNonQuery()方法进行重载,其参数为sql语句及参数组,由于该数组不知无数多少,故要使用params参数
//public static int ExecuteNonQuery(string sql, params SqlParameter[] parameters)
//{
// //使用字符串引用连接符字符串
// string connStr = System.Configuration.ConfigurationManager.AppSettings["ConnStrMaster"].ToString().Trim();
// //string connStr = ConfigurationManager.ConnectionStrings["ConnStrMaster"].ConnectionString;
// //初始化连接符实例
// using (SqlConnection conn = new SqlConnection(connStr))
// {
// conn.Open();//打开连接符
// if (conn.State != ConnectionState.Open)
// {
// MessageBox.Show("数据库打开失败!");
// }
// using (SqlCommand cmd = conn.CreateCommand())//创建一个与连接符关联的操作对象
// {
// cmd.CommandText = sql;//将sql赋值给cmd.CommandText
// MessageBox.Show(sql);
// //foreach (SqlParameter parameter in parameters)//遍历每个参数
// //{
// // cmd.Parameters.Add(parameter);//将每个参数进行传递
// //}
// return cmd.ExecuteNonQuery();//最后将所有返回值return回去
// }
// }
//}
//#endregion
public static int ExecuteNonQuery(string connString, CommandType cmdType, string cmdText, params SqlParameter[] cmdParams)
{
using (var conn = new SqlConnection(connString))
{
var cmd = new SqlCommand();
PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParams);
var count = cmd.ExecuteNonQuery();
//cmd.Parameters.Clear();
return count;
}
}
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParams)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
cmd.CommandType = cmdType;
if (trans != null)
cmd.Transaction = trans;
if (cmdParams != null)
{
foreach (var parm in cmdParams)
{
cmd.Parameters.Add(parm);
}
}
}
private void btn_del_db_Click(object sender, EventArgs e)
{
string connStr = System.Configuration.ConfigurationManager.AppSettings["ConnStrMaster"].ToString().Trim();
string dbName1="ceshi";
string cmdText="DROP DATABASE @dbName";
CommandType cmType = CommandType.Text;
SqlParameter[] parameters =
{
new SqlParameter("@dbName",dbName1)
};
ExecuteNonQuery(connStr, cmType, cmdText, parameters);
MessageBox.Show("数据库删除完成!");
}
}
}
这是用你的,您看下。结果 还是@dbName附近有语法错误。个人感觉还是参数替换的问题。 |
|