我不断收到此错误:System.Data.SqlClient.SqlException:'违反PRIMARY KEY约束' PK__tmp_ms_x__3214EC0750F0A8B2'。无法在对象' dbo.Table'中插入重复键。重复键值为()。
声明已经终止。'
我不知道自己做错了什么,有人知道吗?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace FBLA_Project_1
{
public partial class Form2 : Form
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\LUCY\Documents\testerfile.mdf;Integrated Security=True;Connect Timeout=30");
public Form2()
{
InitializeComponent();
}
private void label3_Click(object sender, EventArgs e)
{
}
private void Form2_Load(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText= "insert into [Table] (Id, Name, EmployeeID, Sunday) values('" + textBox2.Text+"','"+textBox4.Text+"','"+textBox1.Text+"','"+textBox3.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
disp_data();
MessageBox.Show("Data has been put in succefully ");
}
public void disp_data()
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from table ";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
}
}

第33行是我收到错误的地方。经过几个小时的修补和在同一个地方后,它真的很烦人。
答案 0 :(得分:0)
在insertquery中,提供的值的数量(4)与表创建期间定义的列数不匹配 然后你应该明确地指定列名(例如:假设你的列名是col1,col2,col3,col4)
cmd.CommandText="insert into [Table] (col1, col2, col3, col4)
values('"+textBox2.Text+"','"+textBox4.Text+"','"+textBox1.Text+"','"+textBox3.Text+"')";