[英]Trying to insert data into MS Access database using C# but insert command is not working
我的插入命令出错。 我正在尝试将来自 html 页面上的文本框中的用户输入数据添加到我已经创建并连接的访问数据库中。 我的插入命令的语法有问题。
这是我的 HTML 页面
<form name="insert" method="post" action="insertinventory.aspx">
<center>
<h1> FLOATEEZ Add Inventory </h1>
Item Number: <input type="text" name="txtnum"> <br>
Item Name: <input type="text" name="txtname"> <br>
Item Description: <input type="text" name="txtdescription"> <br>
Item Price: <input type="text" name="txtprice"> <br>
Item Quantity on Hand: <input type="text" name="txtqoh"> <br>
Item Picture: (text only) <input type="text" name="txtpicture"> <br><br>
<input type="submit" value="Submit">     <input type="reset">
</center>
</form>
这是我的 aspx 页面减去我的数据库信息
<%@ Page Language="C#" Debug="true" %>
<%@ Import Namespace="System.Data.Odbc" %>
<%
Response.Write("<html><head><title>Insert into Inventory </title></head></body>");
Response.Write("<body bgcolor=lightblue>");
OdbcConnection myconn;
OdbcCommand mycmd;
OdbcDataReader myreader;
myconn= new OdbcConnection( I removed this part );
mycmd = new OdbcCommand("insert into inventory
(Itemnum,Itemname,Itemdescription,Itemprice,Itemqoh,Itempicture) values
('"+ txtnum.Text +"','"+ txtname.Text +"','"+ txtdescription.Text
+"','"+ txtprice.Text +"','"+ txtqoh.Text +"','"+ txtpicture.Text
+"')",myconn);
myreader.Close();
myconn.Close();
%>
<br>
<center> <a href ="Company.html" > Back to our Homepage </a> </center>
一定要使用参数。 问号用于您从用户那里获得的每个值。
下面的示例取自https://www.mikesdotnetting.com/article/26/parameter-queries-in-asp-net-with-ms-access 。 (一个很好的资源。)
string ConnString = Utils.GetConnString();
string SqlString = "Insert Into Contacts (FirstName, LastName) Values (?,?)";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
}
您需要将连接绑定到命令,并调用命令执行语句,例如:
...
mycmd.Connection = myconn;
mycmd.ExecuteNonQuery();
myconn.Close();
无需阅读器。
操作数据库的更好方法是:
using(OdbcConnection myconn = new OdbcConnection(connectionString))
{
using(OdbcCommand mycmd = OdbcCommand(your code here))
{
mycmd.Connection = myconn;
mycmd.ExecuteNonQuery();
}
}
对于using
关键字,它将自动处理连接和命令实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.