For循环插入多个SQL
本文关键字:SQL 插入 循环 For | 更新日期: 2023-09-27 18:16:02
我试图通过SQL与用户插入会话将多行数据插入ms-access
。一旦我实现它keep show SQL INSERT INTO error,我已经检查了我所有的数据类型是正确的。这里需要一些帮助…
按钮:
protected void AddClassBtn_Click(object sender, EventArgs e)
{
string clvl = DropDownList1.SelectedValue;
DateTime Sdate = Calendar1.SelectedDate;
int Nsession = int.Parse(TextBox1.Text);
string Stime = DropDownList2.SelectedValue;
string duration = DropDownList3.SelectedValue;
string desc = TextBox2.Text;
int teacher = int.Parse(DropDownList4.SelectedValue);
DBconn.AddClass(clvl, Sdate, Nsession, Stime, duration, desc, teacher);
}
方法插入SQL:
public static void AddClass(string classlevel, DateTime Sdate,int Nsession, string stime, string duration, string desc, int Tid)
{
int no = Nsession;
for (int i=0; i < no; i++)
{
OleDbConnection myconnection = GetConnection();
DateTime d = Sdate;
d.AddDays(i * 7).ToShortDateString();
string mysql = "INSERT INTO Classes (ClassLevel, StartDate, StartTime, Duration, Desc, TID) VALUES('" + classlevel+"', '"+ d.ToShortDateString()+"'. '"+ stime + "', '"+ duration + "', '"+ desc + "', '"+ Tid + "')";
OleDbCommand mycmd = new OleDbCommand(mysql, myconnection);
try
{
myconnection.Open();
mycmd.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
myconnection.Close();
}
}
}
VALUES('" + classlevel+"', '"+ d.ToShortDateString() +"'. '"+ stime + "', '"+ duration + "', '"+ desc + "', '"+ Tid + "')
你有.
,应该在d.ToShortDateString()
之后去除,用,
代替。也使用命令。参数,以避免将来出现此问题,并保护您免受Sql注入。
string mysql = "INSERT INTO Classes (ClassLevel, StartDate, StartTime, Duration, Desc, TID) VALUES(@ClassLevel, @DateString, @Stime, @Duration, @Desc, @TID)";
OleDbCommand myCmd = new OleDbCommand(mysql, myconnection);
myCmd.Parameters.AddWithValue("@ClassLevel", classlevel);
// my advise is to not store date as string. But you should dicide for yourself!
myCmd.Parameters.AddWithValue("@DateString", d.ToShortDateString());
myCmd.Parameters.AddWithValue("@Stime", stime);
myCmd.Parameters.AddWithValue("@Duration", duration);
myCmd.Parameters.AddWithValue("@Desc", desc);
myCmd.Parameters.AddWithValue("@TID", Tid);
请注意OleDbCommand没有命名参数的概念,所以必须按照与查询相同的顺序定义参数!
修复了ms-access中Desc为保留字的问题。
可以指
https://support.office.com/en us/article/access - 2007 -保留字和符号——e33eb3a9 - 8 baa - 4335 - 9 - f57 da237c63eabe?ui=en US& rs = en-US&广告= US& fromAR = 1