错误:
错误说: - ConnectionString属性尚未出现 在system.data.OledbOledConnection.PermissionDemand()初始化。
我无法弄清楚错误。有人可以解释它是什么意思以及如何解决它?
C#代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;//microsoft database
namespace AccessLoginApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\admin\Documents\Book Database.accdb;
Persist Security Info=False;";
}
catch (Exception ex)
{
MessageBox.Show("Error"+ ex);
}
}
private void button1_Click(object sender, EventArgs e)
{
try{
OleDbConnection connection = new OleDbConnection();
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = " Insert into Book Name(Book Name,Book Number,Publisher) values('" + bookName.Text + "','" + bookNumber.Text + "','" + publisher.Text + "')";
command.ExecuteNonQuery();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
}
}
答案 0 :(得分:2)
表单加载中的变量connection
和button1_Click
事件是类OleDbConnection
的不同实例(显然它们不同)并且您没有使用连接字符串初始化连接变量在button1_Click
事件中(它也导致错误)。如果你这样做意味着你的代码可以正常运行就好,如果用Parameterized
查询替换连锁查询,则意味着你的代码效果很好。引入using
语句将使您的代码完美。您可以尝试以下方法:
string conString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\admin\Documents\Book Database.accdb;Persist Security Info=False;";
// This will be the connection string
private void Form1_Load(object sender, EventArgs e)
{
// Need not to do anything regarding connection
// some other statements if needed
}
private void button1_Click(object sender, EventArgs e)
{
try
{
using (OleDbConnection connection = new OleDbConnection(conString)) // Create and initialize connection object
{
connection.Open();
using (OleDbCommand command = new OleDbCommand())
{
command.Connection = connection;
command.CommandText = " Insert into Book(Book_Name,Book_Number,Publisher) values(@BookName,@BookNumber,@Publisher)";
command.Parameters.Add("@BookName", OleDbType.VarChar).Value = bookName.Text;
command.Parameters.Add("@BookNumber", OleDbType.Integer).Value = bookNumber.Text;
command.Parameters.Add("@Publisher", OleDbType.VarChar).Value = publisher.Text;
command.ExecuteNonQuery();
}
}
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}