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

本文关键字:存储 SQL 数据库 winforms 文本 使用 | 更新日期: 2023-09-27 18:09:45

我试图将tabcontrol中的一组文本框中的值存储到tabcontrol中的另一个tab上的datagridview中,但是代码抛出了以下消息"语法不正确"的异常"系统"。

这是导致错误的代码

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);
            }
        }
    }
}

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

您的网站。CommandText包含一些错误…调试它并获得值!:-)您没有将','放在变量之间,并且您忘记关闭括号…

Like that:

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。(换行)