我正在使用Visual Studio 2010为大学作业创建一个简单的网站。我正在尝试创建一个联系表单,将用户名,电子邮件和消息提交到我的数据库表Messages。
我已经创建了相关的Web服务,我知道当我尝试从表中GET
数据时它正在工作。我对如何INSERT
数据进入表格感到有点困惑。
以下是我的网络服务的代码。我关注的方法是addMessage()
当点击一个位于contact.aspx页面上的按钮时,我调用该方法。
public class Customers : System.Web.Services.WebService {
[WebMethod]
public DataSet getCustomers() {
SqlConnection conn;
SqlDataAdapter myDataAdapter;
DataSet myDataSet;
string cmdString = "Select * From Customers";
conn = new SqlConnection("Data Source=localhost\\SQLEXPRESS;AttachDbFilename=C:\\Users\\n00093500\\Desktop\\MMCA2\\APP_DATA\\NORTHWIND.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
myDataAdapter = new SqlDataAdapter(cmdString, conn);
myDataSet = new DataSet();
myDataAdapter.Fill(myDataSet, "Customers");
return myDataSet;
}
[WebMethod]
public void addMessage(String n, String e, String m)
{
SqlConnection conn;
SqlDataAdapter myDataAdapter;
SqlCommand myCommand = new SqlCommand("INSERT INTO Messages VALUES("+n+","+e+","+m+")");
conn = new SqlConnection("Data Source=localhost\\SQLEXPRESS;AttachDbFilename=C:\\Users\\n00093500\\Desktop\\MMCA2\\APP_DATA\\NORTHWIND.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
//UNSURE WHAT TO DO FROM THIS POINT... CAN I USE myDataAdapter to execute a query?
}
}
感谢你们的帮助!感谢
答案 0 :(得分:5)
[WebMethod]
public void addMessage(String n, String e, String m)
{
string sql = "INSERT INTO Messages VALUES(@n, @e, @m)";
using (var conn = new SqlConnection("Data Source=localhost\\SQLEXPRESS;AttachDbFilename=C:\\Users\\n00093500\\Desktop\\MMCA2\\APP_DATA\\NORTHWIND.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"))
using (var cmd = new SqlCommand(sql, conn))
{
//change these three lines to use actual database column types, lengths
//I'll pretend "e" is a date column just to show an example of how that might look
cmd.Parameters.Add("@n", SqlDbType.NVarChar, 50).Value = n;
cmd.Parameters.Add("@e", SqlDbType.DateTime).Value = DateTime.Parse(e);
cmd.Parameters.Add("@m", SqlDbType.NVarChar, 50).Value = m;
conn.Open();
cmd.ExecuteNonQuery();
}
}