无法将内容插入数据库

时间:2014-01-03 17:21:25

标签: c# sql

我在godaddy中创建了一个sql server数据库,并手动创建了一个名为property的表。我也使用连接string成功地将我的应用程序连接到数据库。但是我无法使用我的c#代码向表中插入任何值 下面是我的C#代码

string strQuery = "INSERT INTO property(name,email,phone,heading,description,location,image1,image2,image3,image4) VALUES('" + name + "','" + email + "','" + phone + "','" + title + "','" + description + "','" + district + "',@data,@data2,@data3,@data4);";
SqlCommand cmd = new SqlCommand(strQuery);


cmd.Parameters.Add("@data", SqlDbType.Binary).Value = bytes;
cmd.Parameters.Add("@data2", SqlDbType.Binary).Value = bytes2;
cmd.Parameters.Add("@data3", SqlDbType.Binary).Value = bytes3;
cmd.Parameters.Add("@data4", SqlDbType.Binary).Value = bytes4;
SqlConnection con = new SqlConnection(constr);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
    con.Open();
    cmd.ExecuteNonQuery();
    return true;
}
catch (Exception ex)
{
    Response.Write(ex.Message);
    return false;
}
finally
{
    con.Close();
    con.Dispose();
}

1 个答案:

答案 0 :(得分:0)

参数化您的查询并稍微清理一下。希望这会有所帮助。

using (SqlConnection con = new SqlConnection("Connection Info"))
{
    // Create your parameterized command.
    SqlCommand cmd = new SqlCommand("INSERT INTO [property] (name, email, phone, heading, description, location, " +
                                    "                        image1, image2, image3, image4) VALUES " +
                                    "                       (@name, @email, @phone, @heading, @description, @location, " +
                                    "                        ,@image1,@image2,@image3,@image4)", con);
    using (cmd)
    {
        // Set your command type.
        cmd.CommandType = CommandType.Text;

        // Add your parameters.
        cmd.Parameters.AddWithValue("@name", "nameParamHere");
        cmd.Parameters.AddWithValue("@email", "emailParamHere");
        // and so on until you complete all params.

        // Execute your command.
        using (SqlDataReader dr = cmd.ExecuteReader()) { };
    }
}

尝试向您的连接字符串“USER ID”授予插入权限。有关详细信息,请参阅此链接... http://beginner-sql-tutorial.com/sql-grant-revoke-privileges-roles.htm

GRANT INSERT 
ON [property] 
TO {user_name} 
[WITH GRANT OPTION];