Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

c# - insert into access database

i have trouble inserting data from textbox into ms access database, I get an error "Syntax error in INSERT INTO."

Can someone help me out please? here's the code:

public void button1_Click(object sender, EventArgs e)//save
{ 
using (OleDbConnection conn = new   
OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data 
Source=|DataDirectory|productdb.mdb"))
{
OleDbCommand CmdSql = new OleDbCommand("Insert into [product](Kod, names, 
price,type,volume,manufacturer,importer)
enter code here
{
conn.Open();
CmdSql.Parameters.AddWithValue("@Kod", textBox1.Text);
CmdSql.Parameters.AddWithValue("@names", textBox2.Text);
CmdSql.Parameters.AddWithValue("@price", textBox3.Text);
CmdSql.Parameters.AddWithValue("@type", textBox4.Text);
CmdSql.Parameters.AddWithValue("@volume", textBox5.Text);
CmdSql.Parameters.AddWithValue("@manufacturer", textBox6.Text);
CmdSql.Parameters.AddWithValue("@importer", textBox7.Text);
CmdSql.ExecuteNonQuery();// i get the error here<<<
conn.Close();
}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are missing the VALUES portion of your insert statement:

OleDbCommand CmdSql = new OleDbCommand("Insert into [product] (Kod, [names], price, type, volume, manufacturer, importer) VALUES (@Kod, @names, @price, @type, @volume, @manufacturer, @importer)", conn);

And you are using Access and OldeDbCommand... so you actually need to use ? instead of a named parameter:

OleDbCommand CmdSql = new OleDbCommand("Insert into [product] (Kod, [names], price, type, volume, manufacturer, importer) VALUES (?, ?, ?, ?, ?, ?, ?)", conn);

See this question for more information.

A side note: Ensure you wrap any reserved keywords in square brackets.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...