将值插入Database.mdf C#

时间:2017-01-09 03:22:25

标签: c# sql sql-server database

我一直在尝试通过datagridView从几个文本框中将值插入Database.mdf SQL Server数据库文件,然后再将它们加载到图表中,但首先它返回了这个错误:

  

System.Data.SqlClient.SqlCommand'不包含的定义   '打开'并且没有扩展方法'打开'接受第一个参数   可以找到类型'System.Data.SqlClient.SqlCommand'(是吗?   缺少using指令或程序集引用?)   C:\ Users \ DELL \ Documents \ Visual Studio   2012 \项目\ WindowsFormsApplication6 \ WindowsFormsApplication6 \ Form1.cs中   65 44 WindowsFormsApplication6

但是那个错误消失了(没有我改变任何代码,只是重新编译它)现在这个函数(即sendrow())实际上没用,什么都不做,甚至没有给出错误。我想如果它设法将它写入数据库,我可以在Form上的datagridView上看到它。

SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder();
csb.ConnectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\DELL\Documents\Visual Studio 2012\Projects\WindowsFormsApplication6\WindowsFormsApplication6\Database1.mdf;Integrated Security=True";

using (SqlConnection conn = new SqlConnection(csb.ConnectionString))
{ 
    conn.Open();

    using (SqlCommand cmd = new SqlCommand("INSERT INTO Stocks (Open, High, Low, Close, Day) VALUES (@Open, @High, @Low, @Close, @Day)"))
    {
        cmd.CommandType = CommandType.Text;
        cmd.Connection = conn;

        // cmd.Parameters.Add(new SqlParameter("@Open", SqlDbType.VarChar, 40));    //using this way "The variable name '@Open' has already been declared. Variable names must be unique within a query batch or stored procedure."
        // cmd.Parameters.AddWithValue("@Open", textBox13.Text);
        cmd.Parameters.AddWithValue("@Open", textBox13.Text);          
        cmd.Parameters.AddWithValue("@High", textBox14.Text);
        cmd.Parameters.AddWithValue("@Low", textBox15.Text);
        cmd.Parameters.AddWithValue("@Close", textBox16.Text);

        cmd.ExecuteNonQuery();   // Incorrect syntax near the keyword 'Open'.
    }

    stocksTableAdapter.Update(database.Stocks); //LINE***added later but still getting "Incorrect syntax near the keyword 'Open'."
}

在数据库中,添加了一个名为Stocks的表,其中包含5列(Id, Open, High, Low, Close)。如果我遗漏了一些明显的东西,我很抱歉,因为我对SQL Server还不熟悉。数据库是作为基于服务的数据库创建的,除了创建Open, High, Low, Close, Day列并将其输入定义为Decimal(18,4) Open, High, Low, CloseDatetime Day之外,没有给出任何值。 1}}(但这不是代码中的任何值)

3 个答案:

答案 0 :(得分:1)

OpenClosereserved T-SQL keywords,您应将其用作表格和/或列名称。尝试为您的业务案例使用更直观的内容 - 例如OpenValueCloseValue或类似的东西。

如果坚持使用这些名称,那么必须将它们放在方括号中:[Open][Close]

string query = "INSERT INTO dbo.Stocks ([Open], High, Low, [Close], Day) " +
               "VALUES (@Open, @High, @Low, @Close, @Day);"; 

using (SqlCommand cmd = new SqlCommand(query, conn))
{
    .....
} 

答案 1 :(得分:0)

试试这个

cmd.Parameters.Add(new SqlParameter("@Open", "Value"));

答案 2 :(得分:0)

不应该更像这样吗?

com.CommandText = (@"INSERT INTO Stock (Prod_ID, Prod_Name, Prod_Cat, Supplier, Cost, Price_1, Price_2, Price_3) VALUES ('"+ProdID.Text+"','"+ProdName.Text+"','"+ProdCat.Text+"','"+ProdSup.Text+"','"+ProdCost.Text+"','"+ProdPrice1.Text+"','"+ProdPrice2.Text+"','"+ProdPrice3.Text+"');"));

只是一个例子......