INSERT语句不会将数据插入表中

时间:2012-05-24 14:51:14

标签: c# sql-server

我对INSERT语句有疑问。我从gridviev获取数据并且工作正常,但我无法将它们插入表

private void button3_Click(object sender, EventArgs e)
{
    int amorplanid = 0;
    int idn = 0;
    DateTime datum;
    double interest = 0;
    double principal = 0;
    double payment = 0;
    double newprincipal = 0;

    string nizz = "";
    string[] niz= new string[7];
    for (int x = 0; x < dataGridView1.Rows.Count-1; x++)
    {
        for (int j = 0; j < dataGridView1.Rows[x].Cells.Count; j++)
        {
            nizz += dataGridView1.Rows[x].Cells[j].Value.ToString()+"."; 
        }
        niz = nizz.Split('.');

        amorplanid = System.Convert.ToInt32(niz[0]);
        idn = System.Convert.ToInt32(niz[1]);
        // datum = System.Convert.ToDateTime(niz[2]);
        datum = DateTime.Now;
        interest = System.Convert.ToDouble(niz[3]);
        principal = System.Convert.ToDouble(niz[4]);
        payment = System.Convert.ToDouble(niz[5]);
        newprincipal = System.Convert.ToDouble(niz[6]);

        String insert = @"INSERT INTO AmortPlanCoupT(ID, AmortPlanID, CoupDate, Interest, Principal, Payxment, NewPrincipal) VALUES (" + idn + "," + amorplanid + "," + datum + "," + (float)interest + "," + (float)principal + "," + (float)payment + "," + (float)newprincipal + ")";
        SqlConnection myconn = new SqlConnection(conn);
        // String MyString = @"INSERT INTO Employee(ID, FirstName, LastName) VALUES(2, 'G', 'M')";
        try
        {
            myconn.Open();
            SqlCommand cmd = new SqlCommand(insert, myconn);
            cmd.ExecuteNonQuery();
            myconn.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

    label14.Text = niz[0];
}

我创建了一个Windows控制台应用来测试:

我的表test有两列id (int) , leto (float);

SqlConnection MyConnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\App_Data\Database1.mdf;Integrated Security=True;User Instance=True");

try
{
    MyConnection.Open();

    String MyString = @"INSERT INTO test(id, leto) VALUES(2, 2)";
    SqlCommand MyCmd = new SqlCommand(MyString, MyConnection);

    MyCmd.ExecuteScalar();
    MyConnection.Close();
}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}

我一直在尝试使用不同的东西将数据写入表格,但却无法将数据写入表格。

2 个答案:

答案 0 :(得分:5)

正如我之前在此网站上所说的那样 - 整个用户实例和AttachDbFileName = 方法存在缺陷 - 充其量! Visual Studio将围绕.mdf文件和最有可能进行复制,您的INSERT工作正常 - 但您只是查看错误的.mdf文件< / strong>到底!

如果你想坚持这种方法,那么尝试在myConnection.Close()调用上设置一个断点 - 然后用SQL Server Mgmt Studio Express检查.mdf文件 - 我几乎可以肯定你的数据在那里。

我认为真正的解决方案将是

  1. 安装SQL Server Express(你已经完成了)

  2. 安装SQL Server Management Studio Express

  3. SSMS Express 中创建数据库,为其指定一个逻辑名称(例如Database1

  4. 使用其逻辑数据库名称(在服务器上创建时给定)连接到它 - 并且不要乱用物理数据库文件和用户实例。在这种情况下,您的连接字符串将类似于:

    Data Source=.\SQLEXPRESS;Database=Database1;Integrated Security=True
    

    其他所有内容都完全与以前相同......

答案 1 :(得分:-1)

在继续之前,您应该重写代码以使用参数,而不是字符串连接。