这是我在c#中创建的Sql函数类。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
using System.Windows.Forms;
namespace DatabaseTest
{
static class SQLFunctions
{
static private SqlConnection dbconnect = new SqlConnection(@"Data Source=sourcecode_guy-pc\sqlexpress;Initial Catalog=test;Integrated Security=True");
static public void Delete(object button) // This is the *Delete Function*
{
try
{
dbconnect.Open();
int IsDeleted;
SqlCommand DeleteAllQuery = new SqlCommand("DELETE FROM users", dbconnect);
DeleteAllQuery.ExecuteNonQuery();
IsDeleted = (int)DeleteAllQuery.ExecuteScalar();
if (IsDeleted == 0)
{
MessageBox.Show("Database has been truntcated.");
}
else if(IsDeleted == 1)
{
MessageBox.Show("An error has occured and your database table was not deleted.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
dbconnect.Close();
}
}
}
}
这是我表单中的删除按钮
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;
namespace DatabaseTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnDelete_Click(object sender, EventArgs e)
{
SQLFunctions.Delete(button: btnDelete);
}
}
}
当我运行程序时,它给了我一个 System.NullReferenceException:对象引用未设置为对象的实例。 在中的DatabaseTest.SQLFunctions.Delete(对象按钮) C:\我的路径:)
答案 0 :(得分:0)
您的代码执行命令两次。
DeleteAllQuery.ExecuteNonQuery();
IsDeleted = (int)DeleteAllQuery.ExecuteScalar();
删除其中一个。