c# - 它说command.ExecuteNonQuery()未初始化

标签 c# ado.net

我的代码:

// Get Connection String
string conn = WebConfigurationManager.ConnectionStrings["GraduatesConnectionString"].ToString();
// Create connection object
SqlConnection connection = new SqlConnection(conn);
SqlCommand command = connection.CreateCommand();
try
{
    // Open the connection.
    connection.Open();
    // Execute the insert command.
    command.CommandText = ("INSERT INTO PersonalInfo(Id,Name,LastName,ContactNumber, Address,Gender, Date_Of_Birth) VALUES(\'"
                + (this.txtID.Text + ("\',\'"
                + (this.txtName.Text + ("\',\'"
                + (this.txtLastName.Text + ("\',\'"
                + (this.txtContactNumber.Text + ("\',\'"
                + (this.txtAddress.Text + ("\',\'"
                + (this.gender + ("\',\'"
                + (this.txtDateofBirth.Text + ("\',\'"
             )))));
    command.ExecuteNonQuery();
}
finally
{
    // Close the connection.
    connection.Close();
}

最佳答案

using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
    command.CommandText = "INSERT INTO PersonalInfo (Id, Name, LastName, ContactNumber, Address, Gender, Date_Of_Birth) VALUES (@Id, @Name, @LastName, @LastName, @Address, @Gender, @DateOfBirth)";

    command.Parameters.AddWithValue("@Id", txtID.Text);
    ...

    connection.Open();
    command.ExecuteNonQuery();
}

关于c# - 它说command.ExecuteNonQuery()未初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12473217/

相关文章:

c# - Unity3d c# 帮助,产生 itempickups

c# - WCF 服务在 JavaScript 中返回 "is undefined"

c# - C#调用存储过程

c# - 带循环的sql事务,一条commit语句

具有 WCF 数据的 WPF 应用程序 - EF、Linq2Sql 或 WCF 数据服务 - 无似乎 'Easy'

c# - SqlException 在 C# 中未处理 - 数据库表中的信息

c# - Quartz.NET 在随机持续时间后停止触发

c# - 如何禁用 WPF TreeView 中的双击行为?

C# UWP - 如何从另一个页面访问页面控件?

c# - .NET - 如何从数据集中检索特定项目?