我想创建一个保存/删除/编辑数据库文件的程序。例如,我想将此信息输入数据库:
Name: John
Surname: Johnson
Father's name: Johnson
Offers used: 10
Age: 20
所有这些都将被保存,编辑或删除。但是当我尝试做这个
我收到此错误:
System.Data.dll中发生了类型为'System.Data.SqlClient.SqlException'的未处理的异常
附加信息:关键字“ 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 Photography_Register
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Ivan\Documents\db.mdf;Integrated Security=True;Connect Timeout=30");
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Table values('"+textBox1.Text+"','"+textBox2.Text+"','"+textBox3.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data about " + textBox1.Text + " " + textBox3.Text + " has been successfully" + "\r" + "uploaded to server!");
}
}
}
答案 0 :(得分:3)
Table
是T-SQL的保留字。如果确实是表的名称,则需要在[ ]
之间编写它。
喜欢这个。
insert into [Table] values
...
使用第二个问题的参数更新(列数不正确...)
How do I to insert data into an SQL table using C# as well as implement an upload function?
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO [Table] (ColumnName1, ColumnName2, ColumnName3, ColumnName4, ColumnName5) VALUES (@ColumnName1, @ColumnName2, @ColumnName3, @ColumnName4, @ColumnName5)";
cmd.Parameters.AddWithValue("@ColumnName1", textBox1.Text);
cmd.Parameters.AddWithValue("@ColumnName2", textBox2.Text);
cmd.Parameters.AddWithValue("@ColumnName3", textBox3.Text);
cmd.Parameters.AddWithValue("@ColumnName4", textBox4.Text);
cmd.Parameters.AddWithValue("@ColumnName5", textBox5.Text);
cmd.ExecuteNonQuery();
con.Close();
只需将ColumnName1
ColumnName2
...替换为列名,将textBox1.Text
,textBox2.Text
...替换为输入文本框
如果列与textboxX.Text
类型不匹配,请不要忘记将string
强制转换为所需的数据类型。
https://docs.microsoft.com/es-es/dotnet/api/system.int32.parse?view=netframework-4.7.2
cmd.Parameters.AddWithValue("@ColumnName4", int.Parse(textBox4.Text));
cmd.Parameters.AddWithValue("@ColumnName5", int.Parse(textBox5.Text));