中运行它。
我需要构建一个应用程序,人们可以在其中进行预订,但在此之前,他们需要填写一些信息。当我试图保存数据时,我得到了这个错误代码:类型为"System.Data.SqlClient"的未处理异常。SqlException' occurred in System.Data.dll
这是我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BonTemps
{
public partial class Home : Form
{
public Home()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var Form1 = new Form1();
Form1.Show();
}
private void tabPage1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void Home_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'bonTempsDBDataSet.Tafel' table. You can move, or remove it, as needed.
this.tafelTableAdapter.Fill(this.bonTempsDBDataSet.Tafel);
}
private void btnOpslaan_Click(object sender, EventArgs e)
{
SqlConnection sc = new SqlConnection();
SqlCommand com = new SqlCommand();
sc.ConnectionString = ("Data Source=ACER;Initial Catalog=BonTempsDB;Integrated Security=True");
sc.Open();
com.Connection = sc;
com.CommandText = (@"INSERT INTO Klant (Naam, Adres, Woonplaats, Telefoonnummer, EmailAdres), VALUES ('" + txtNaam.Text + "','" + txtAdres.Text + "','" + txtWoon.Text + "','" + txtTel.Text + "','" + txtMail.Text + "'");
com.ExecuteNonQuery();
sc.Close();
}
}
}
去掉VALUES前的逗号。
如果这还不够,您可以调试并复制从命令文本中生成的字符串,并尝试直接在SQL Server management Studio或类似的
排版错误请删除VALUES前的逗号
您必须将打开的SqlConnection传递给SqlCommand以使其工作:
com.Connection = sc;
另外,考虑使用命名参数将数据传递给查询,以使查询更防错误:
SqlConnection sc = new SqlConnection();
SqlCommand com = new SqlCommand();
sc.ConnectionString = ("Data Source=ACER;Initial Catalog=BonTempsDB;Integrated Security=True");
sc.Open();
com.Connection = sc;
com.CommandText = @"INSERT INTO Klant (Naam, Adres, Woonplaats, Telefoonnummer, EmailAdres) VALUES (@naam, @adres, @woon, @tel, @mail)";
com.Parameters.AddWithValue("@naam", txtNaam.Text);
com.Parameters.AddWithValue("@adres", txtAdres.Text);
com.Parameters.AddWithValue("@woon", txtWoon.Text);
com.Parameters.AddWithValue("@tel", txtTel.Text);
com.Parameters.AddWithValue("@mail", txtMail.Text);
com.ExecuteNonQuery();
sc.Close();
using (var sc = new SqlConnection("Data Source=ACER;Initial Catalog=BonTempsDB;Integrated Security=True"))
{
using (var com = new SqlCommand("sql cmd text", sc))
{
try
{
sc.Open();
com.ExecuteNonQuery();
}
catch
{
}
}
}