gpt4 book ai didi

c# - 错误 - 连接字符串属性尚未初始化(C# 数据库)?

转载 作者:行者123 更新时间:2023-11-30 23:18:22 24 4
gpt4 key购买 nike

错误:

The error says:- The ConnectionString Property has not been initialized at 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);
}

}




}
}

最佳答案

表单加载中的变量connectionbutton1_Click事件是类OleDbConnection的不同实例(显然它们是不同的)和你尚未在 button1_Click 事件中使用连接字符串初始化连接变量(这也会导致错误)。如果你这样做意味着你的代码将运行良好,如果你将串联查询替换为参数化查询意味着你的代码将运行良好。而 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);
}

}

关于c# - 错误 - 连接字符串属性尚未初始化(C# 数据库)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40967122/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com