我想将JSON数据插入sql服务器表中,我通过URL检索json数据,并且通过明显的错误{"Must declare the scalar variable \"@Name\"."}
在按钮click事件中写入了插入逻辑,因为我不提供任何用于插入数据的参数,因为我无法通过硬编码来传递这些参数
private string HttpContent(string url)
{
WebRequest objRequest = System.Net.HttpWebRequest.Create(url);
StreamReader sr = new StreamReader(objRequest.GetResponse().GetResponseStream());
string result = sr.ReadToEnd();
sr.Close();
return result;
}
protected void btnsave_Click(object sender, EventArgs e)
{
var conString = ConfigurationManager.ConnectionStrings["SQLDBConnection"];
string strConnString = conString.ConnectionString;
SqlConnection conn = new SqlConnection(strConnString);
SqlCommand com;
string data = HttpContent(txturl.Text);
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
var table = jsSerializer.Deserialize<dynamic>(data);
conn.Open();
com = new SqlCommand("INSERT INTO tbl_insert_json (Name, Mobile, Email) VALUES(@Name, @Mobile, @Email)", conn);
com.CommandType = CommandType.Text;
int refId = com.ExecuteNonQuery();
conn.Close();
if (refId > 0)
{
Response.Write("{\"response\":{\"status\":\"success\",\"msg\":\"Details Saved Successfully..\"}}");
}
else
{
Response.Write("{\"response\":{\"status\":\"fail\",\"msg\":\"oops!! something went wrong\"}}");
}
}
现在我的问题是我应该更改什么或如何将数据插入sql server表
我在每个循环中使用它来映射每一行,然后插入但对我不起作用请分享任何想法或方法将数据插入表中?我在com = new SqlCommand("INSERT INTO tbl_insert_json (Name, Mobile, Email) VALUES(@Name, @Mobile, @Email)", conn);
本节中遇到问题,如何将这些参数插入表中
答案 0 :(得分:0)
必须在SqlCommand对象的实例行之后添加参数以用json值替换参数,例如:
com = new SqlCommand("INSERT INTO tbl_insert_json (Name, Mobile, Email) VALUES(@Name, @Mobile, @Email)", conn);
com.Parameters.Add("@Name", SqlDbType.NChar);
com.Parameters["@Name"].Value = "NameDataJson";
com.Parameters.Add("@Mobile", SqlDbType.NChar);
com.Parameters["@Mobile"].Value = "MobileDataJson";
com.Parameters.Add("@Email", SqlDbType.NChar);
com.Parameters["@Email"].Value = "EmailDataJson";