使用参数将数据插入本地数据库

时间:2015-04-10 06:26:04

标签: c# mysql

大家好,我已经被困在这两天了。我正在使用Visual Studio 2013并制作了一个Windows窗体项目。然后使用以下代码我试图插入值,但是"显示表数据" option生成一个包含空值的表。我做错了什么?

        SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.
 ConnectionStrings["WindowsFormsApplicationtodatabase.Properties.Settings.DatabasewebConnectionString"].ConnectionString);

        conn.Open();

        using (conn)
        {
            SqlCommand cmd = new SqlCommand("INSERT INTO webtable (Id, url_name) VALUES (@id, @url)");
            cmd.CommandType = CommandType.Text;
            cmd.Connection = conn;
            cmd.Parameters.AddWithValue("@url", "nagia");
            cmd.Parameters.AddWithValue("@id", "9");

            cmd.ExecuteNonQuery();
        }

3 个答案:

答案 0 :(得分:1)

你可以试试这个

 conn.Open();

 string strQuery = "INSERT INTO webtable (Id, url_name) VALUES (@id, @url)";
 SqlCommand cmd = new SqlCommand(strQuery, conn);
 cmd.Parameters.AddWithValue("@url", "nagia");
 cmd.Parameters.AddWithValue("@id", "9");
 cmd.Connection = conn;
 cmd.ExecuteNonQuery();
 conn.Close();

答案 1 :(得分:0)

尝试为参数指定数据类型。

参考,

[SqlCommand Parameters Add vs. AddWithValue

答案 2 :(得分:0)

您可以尝试此代码..

using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["WindowsFormsApplicationtodatabase.Properties.Settings.DatabasewebConnectionString"].ConnectionString));
{

SqlCommand cmd = new SqlCommand("INSERT INTO webtable (Id, url_name) VALUES (@id, @url)",conn);

cmd.Parameters.AddWithValue("@url", "nagia");
cmd.Parameters.AddWithValue("@id", "9");
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();

}