大家好我试图将从前端获取的值插入到sql server database.here是我的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Geocoding.Google;
using Geocoding;
using System.Data.SqlClient;
public partial class regforswa : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string lat;
string longi;
IGeocoder geocoder = new GoogleGeocoder() { };
Address[] addresses =
geocoder.Geocode(TextBox4.Text+TextBox5.Text+TextBox6.Text).ToArray();
foreach (Address adrs in addresses)
{
//Response.Write("lat=" +adrs.Coordinates.Latitude.ToString());
//Response.Write( "longi="+ adrs.Coordinates.Longitude.ToString());
}
SqlConnection conn = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=swa1;User Id=swa1;Password=swa1;");//datasource=localhost name,initial catalog=db name
//integrated security=windiws authentication OR for sql authentication specify
//userid and password
conn.Open();//opens connection with the database
try
{//exeption handling
String uname=TextBox1.Text;
String pwd=TextBox3.Text;
String mnumber = TextBox7.Text;
String sques = DropDownList1.Text;
String res = TextBox8.Text;
String adress = TextBox4.Text;
String cty = TextBox5.Text;
String zpcode = TextBox6.Text;
// Response.Write("uname"+uname +"pwd"+ pwd);
SqlCommand newcomm = new SqlCommand("INSERT INTO regforswa(username,password,mno,sq,response,address,city,zipcode) VALUES (uname,pwd,mnumber,sques,res,adress,cty,zpcode)", conn);
if (newcomm.ExecuteNonQuery() == 1)
{
result.Visible = true;
result.Text = "entered successfully";
}
else
{
result.Text = "not entered";
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
}
}
}
但我收到此错误
列名无效' uname'。列名称无效' pwd'。列无效 姓名' mnumber'。列名称无效' sques'。列名无效 ' RES&#39 ;.列名称无效'地址'列名称无效' cty'。 列名称无效' zpcode'。
我检查了我的数据库列名,这很完美。请有人帮忙。为什么我得到这个错误?
答案 0 :(得分:0)
在INSERT命令中,您无法以这种方式直接传递变量值。使用参数占位符,然后构建命令的参数集合
string uname=TextBox1.Text;
string pwd=TextBox3.Text;
string mnumber = TextBox7.Text;
string sques = DropDownList1.Text;
string res = TextBox8.Text;
string adress = TextBox4.Text;
string cty = TextBox5.Text;
string zpcode = TextBox6.Text;
SqlCommand newcomm = new SqlCommand(@"INSERT INTO regforswa
(username,password,mno,sq,response,address,city,zipcode) VALUES
(@uname,@pwd,@mnumber,@sques,@res,@adress,@cty,@zpcode)", conn);
newcomm.Parameters.AddWithValue("@uname", uname);
..... and so on for the other parmaters required by the placeholders
if (newcomm.ExecuteNonQuery() == 1)
另外,请记住,应该准确输入您的字段所需的参数。例如,如果字段mno的类型为整数,则需要转换该参数的值
newcomm.Parameters.AddWithValue("@mnumber", Convert.ToInt32(mnumber));