【发布时间】:2019-12-27 01:22:10
【问题描述】:
我想将新的 ID-Machine(不是自动的)、新机器的名称并选择该类型机器所属的区域(Bereich)放入一个列表中。 我尝试将 ID 号(如在数据库访问中)字符串更改为 ID 以获取 INSERT INTO 查询中的区域名称。但是我不知道为什么VS显示我没有打开连接(ExecuteNonQuery需要一个打开且可用的连接。连接的当前状态是关闭的)...如果有人可以帮助我,那就太好了。
public void bttnSpeichern_Click_1(System.Object sender, EventArgs e)
{
Module.con.Open();
int geraetid = (int)(Conversion.Val(lblGeraetid.Text));
int bereichid = (int)(Conversion.Val(lblBereichID.Text));
if (lblGeraetid.Text == "MaschineID" || lblGeraetid.Text == null || txtGeraetName.Text == null || lblGeraetid.Text == "BereichID" || lblBereichID.Text == null)
{
Interaction.MsgBox("Bitte füllen Sie die Faldern aus", Constants.vbInformation, "Hinweis");
}
else
{
string b = System.Convert.ToString(Interaction.MsgBox("Möchten Sie die Eingaben bestätigen?", (int)Constants.vbQuestion + Constants.vbYesNo, "Anlegen"));
if ( b == Constants.vbYes.ToString())
{
Module.con.Open();
OleDbCommand geraete_anlegen = new OleDbCommand("INSERT INTO tblMaschine(MaschineID,Maschine,BereichID) VALUES (\'"+
lblGeraetid.Text + "\',\'"+
txtGeraetName.Text + "\',\'" +
lblBereichID.Text + "\',\'", Module.con);
geraete_anlegen.ExecuteNonQuery();
Interaction.MsgBox("Gerät wurde erfolgreich angelegt!", Constants.vbInformation, "Neues Gerät");
//clear_text();
Module.con.Close();
display_geraete();
}
}
}
【问题讨论】:
-
能把
Module类相关的代码放上来吗? -
不要像那样打开你的连接。将这些一次性物品放入 using-block 中。使用参数避免sql注入和格式错误。
-
@萨曼:使用系统;使用 System.Collections.Generic;使用 System.Linq;使用 System.Text;使用 System.Threading.Tasks;使用 System.Data.OleDb; namespace Geraetverleich { public class Module { public static OleDbConnection con = new OleDbConnection("Provider=MICROSOFT.ACE.OLEDB.12.0; Data Source=|DataDirectory|/Geraetverleih.accdb"); } }
-
@Lars,但这是在哪里打开的?我想我用“Module.con.Close(); 关闭它吗?
-
你没有关闭它
if (lblGeraetid.Text == "MaschineID" ...
标签: c# winforms oledbconnection executenonquery