我正在为资产管理数据库应用程序为我的公司。我没有一吨的用SQL或MS访问数据库的管理经验。我工作的一个解决方案,将数据添加到使用C#在Visual Studio中有它运行SQL命令数据库。我在一些文本框的工作揭示,如果我的代码是或不是在不同的地方跑,我有(我认为)范围缩小到我的SQL,虽然我不知道肯定不,我还没有发现太多有关访问和OLEDB通过搜索。
我已经改变了资本和措辞,以及逗号和报价为我的SQL代码,以及在我的错误可能由代码捕获的地方烘烤。
private void SubmitButton_Click(object sender, EventArgs e)
{
try
{
//declares connection
OleDbConnection con = new OleDbConnection();
OleDbCommand command = new OleDbCommand();
con.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\eric.varner\Documents\AssetDB.accdb";
//open connection to Database
con.Open();
StatusLabel.Text = "Connected";
//declares command type
command.Connection = con;
//SQL commands to call database to write data.
if (AssetTypeBox.Text == "iPad")
{
command.CommandText = "INSERT INTO AssetsiPad (Asset Tag, Condition, Location, Serial Number) VALUES('" + AssetBox.Text + "','" + ConditionBox.Text +
"','" + LocationBox.Text + "','" + SerialNumBox.Text + "')";
MessageBox.Show("The if statement runs fine");
}
else if (AssetTypeBox.Text == "iPhone")
{
command.CommandText = "INSERT INTO AssetsiPhone (Asset Tag, Condition, Location, Serial Number) VALUES('" + AssetBox.Text + "','" + ConditionBox.Text +
"','" + LocationBox.Text + "','" + SerialNumBox.Text + "')";
}
else if (AssetTypeBox.Text == "MR AP")
{
command.CommandText = "INSERT INTO AssetsMR (Asset Tag, Condition, Location, Serial Number, MAC Address, IP Address) VALUES('" + AssetBox.Text + "','"
+ ConditionBox.Text + "','" + LocationBox.Text + "','" + SerialNumBox.Text + "','" + MACaddressBox.Text + "','" + IPsubnetBox.Text + "')";
}
else if (AssetTypeBox.Text == "MX Security")
{
command.CommandText = "INSERT INTO AssetsMX (Asset Tag, Condition, Location, Serial Number) VALUES('" + AssetBox.Text + "','" + ConditionBox.Text + "','"
+ LocationBox.Text + "','" + SerialNumBox.Text + "',)";
}
else if (AssetTypeBox.Text == "Laptop")
{
command.CommandText = "INSERT INTO AssetsLaptop (Asset Tag, Condition, Location, Serial Number) VALUES('" + AssetBox.Text + "','" + ConditionBox.Text + "','"
+ LocationBox.Text + "','" + SerialNumBox.Text + "',)";
}
else
{
MessageBox.Show("you aren't reaching the correct statement");
}
command.ExecuteNonQuery();
//close connection to Database
con.Close();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
StatusLabel.Text = "Not Connected";
MessageBox.Show("your sql didn't run correctly");
}
}
当我进入我的琴弦正确如的“iPad”我得到的消息框是说“if语句运行良好”和“您的SQL没有正常运行。”该AssetTypeBox是,我有什么样的内置捕获的唯一的事情。其他字段应该能够接受数据的任何类型或数量没有问题。我希望我没有留下任何出来。
我认为INSERT
命令不能接受包含空格的字段名称,除非你用方括号括起来:
[Asset Tag]
The if statement runs fine
Your SQL didn't run correctly
上述结果是相当期待。当您运行command.ExecuteNonQuery();
这意味着你没有这个点之前得到例外您的SQL查询被执行。
if语句与iPad检查,并满足该MessageBox.Show("The if statement runs fine");
代码执行command.ExecuteNonQuery();
和异常发生后运行。
既然你有异常块,错误是由下面的代码来处理
StatusLabel.Text = "Not Connected";
MessageBox.Show("your sql didn't run correctly");