使用c#winforms将文本框值存储到SQL数据库中

时间:2013-04-17 14:53:48

标签: c# winforms

我正在尝试将tabcontrol中的一组文本框中的值存储到tabcontrol中的anothertab上的datagridview中,但是代码会抛出异常,并显示以下消息“System'附近的语法不正确。”

这是导致错误的代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Windows_8_Login
{
    public partial class Stock : Form
    {
        public Stock()
        {
            InitializeComponent();
        }

        private void Stock_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'loginScreenDataSet7.Stock' table. You can move, or remove it, as needed.
            this.stockTableAdapter1.Fill(this.loginScreenDataSet7.Stock);


        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
            Form dash = new DashBoard();
            dash.Show();

        }



        private void GenButton_Click(object sender, EventArgs e)
        {
            Random Gen = new Random();
            ProdID.Text = Convert.ToString(Gen.Next(1000000, 9000000));
        }

        private void SaveBtn_Click(object sender, EventArgs e)
        {
            try
           {
                SqlConnection sc = new SqlConnection();
                SqlCommand com = new SqlCommand();
                sc.ConnectionString = ("Data Source=localhost;Initial Catalog=LoginScreen;Integrated Security=True");
                sc.Open();
                com.Connection = sc;
                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 + "" + ProdPrice3.Text + "");
                com.ExecuteNonQuery();
                sc.Close();
           }
            catch (Exception x)
            {
               MessageBox.Show(x.Message);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

你的com.CommandText包含一些错误...... 调试它并获得价值! :-) 你没有在vars之间放置','而你忘了关闭括号......

就像那样:

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
  + ")");

但是,您应该使用SqlParameters。 (和换行符)

相关问题