首页 > 解决方案 > 也不例外,但我的数据没有写入 SQL Server 数据库

问题描述

在将新数据条目插入 SQL Server 数据库时,我陷入了困境。我有我想存储在以下课程中的所有信息:

public class NewSearchQuery //object reference q
{
    public string Name, Location, SearchType, Path, Method;
    public int RefNum;
    public double Fee;
    public bool Paid;
}

在用户填写表格等之后。这是我将信息保存到数据库的代码:

        bool complete;
        string sql = $"Insert into PrivateLog (Id,Applicant,ApplicationDate,Location,Search,Paid,Method,Amount,Files) values({q.RefNum}, '{q.Name}', {AppDate}, '{q.Location}', '{q.SearchType}', {q.Paid}, '{q.Method}', {q.Fee}, '{q.Path}')";
        cnn.Open();
        try
        {
            SqlDataAdapter adapter = new SqlDataAdapter();
            SqlCommand command = new SqlCommand(sql, cnn); //The Connection String cnn is in a public string variable above this method. 
            adapter.InsertCommand = new SqlCommand(sql, cnn);
            command.Dispose();
            complete = true;
        }
        catch (System.Exception e)
        {
            complete = false;
        }
        cnn.Close();
        return complete;

这是我的表设计器的样子:

在此处输入图像描述

谁能告诉我为什么新的数据输入可能无法通过?

标签: c#sql-serverdatabasesql-insert

解决方案


在这种情况下,您不需要 SqlDataAdapter,您可以简单地执行您的命令:

try
{
    SqlCommand command = new SqlCommand(sql, cnn);
    command.ExecuteNonQuery();
    complete = true;
}

尽管我建议使用 command.Parameters 添加参数值,以保护可能的 SQL 注入:

bool complete;
string sql = "Insert into PrivateLog (Id, Applicant, ApplicationDate, Location, Search, Paid, Method, Amount, Files) values(@RefNum, @Name, @AppDate, @Location, @SearchType, @Paid, @Method, @Fee, @Path)";
cnn.Open();
try
{
    SqlCommand command = new SqlCommand(sql, cnn);

    command.Parameters.Add("@RefNum", SqlDbType.Int).Value = q.RefNum;
    command.Parameters.Add("@Name", SqlDbType.VarChar).Value = q.Name;
    command.Parameters.Add("@AppDate", SqlDbType.DateTime).Value = AppDate;
    command.Parameters.Add("@Location", SqlDbType.VarChar).Value = q.Location;
    command.Parameters.Add("@SearchType", SqlDbType.VarChar).Value = q.SearchType;
    command.Parameters.Add("@Paid", SqlDbType.Bit).Value = q.Paid;
    command.Parameters.Add("@Method", SqlDbType.VarChar).Value = q.Method;
    command.Parameters.Add("@Fee", SqlDbType.Decimal).Value = q.Fee;
    command.Parameters.Add("@Path", SqlDbType.VarChar).Value = q.Path;

    command.ExecuteNonQuery();
    command.Dispose();
    complete = true;
}
catch (System.Exception e)
{
    complete = false;
}
cnn.Close();
return complete;

推荐阅读