我目前收到的错误是: System.InvalidOperationException:'ConnectionString属性尚未初始化。' 我想要一些帮助来解决这个问题,因为我试图将数据从c#表单(多个文本框)输入到SQL数据库表格,我当前的代码是
private void AcceptData()
{
using (Connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("INPUT INTO Person", Connection))//, Connection
{
DataTable RegisterTable = new DataTable();
adapter.Fill(RegisterTable); //System.InvalidOperationException: 'The ConnectionString property has not been initialized.' TO FIX
string name = textBox1.Text;
string organisation = textBox3.Text;
DateTime Time = DateTime.Parse(textBox2.Text);
string strDateTimeIn = Time.ToString("yyyy-MM-dd HH:mm:ss.ffff");
string query = "INSERT INTO Person (Name,Organisation,TimeIn) VALUES('" + name + "','" + organisation + "','" +strDateTimeIn+ "')";
SqlCommand SignIn = new SqlCommand(query,Connection);
SignIn.ExecuteNonQuery();
}
}
任何帮助将不胜感激
使用的连接字符串是:string connectionString = (@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Register.mdf;Integrated Security=True");
答案 0 :(得分:3)
您需要打开连接
using (Connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlDataAdapter adapter = new SqlDataAdapter("INPUT INTO Person", Connection))//, Connection
{
DataTable RegisterTable = new DataTable();
adapter.Fill(RegisterTable); //System.InvalidOperationException: 'The ConnectionString property has not been initialized.' TO FIX
string name = textBox1.Text;
string organisation = textBox3.Text;
DateTime Time = DateTime.Parse(textBox2.Text);
string strDateTimeIn = Time.ToString("yyyy-MM-dd HH:mm:ss.ffff");
string query = "INSERT INTO Person (Name,Organisation,TimeIn) VALUES('" + name + "','" + organisation + "','" +strDateTimeIn+ "')";
SqlCommand SignIn = new SqlCommand(query,Connection);
SignIn.ExecuteNonQuery();
}
}
答案 1 :(得分:0)
“尚未初始化ConnectionString属性”清楚地表明在方法内未正确分配用于打开SqlConnection
的连接字符串属性。要解决此问题,请在方法体中分配连接字符串,如下所示:
private void AcceptData()
{
// assumed the connection string obtained from app.config or web.config file
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
using (SqlConnection Connection = new SqlConnection(connectionString))
{
Connection.Open(); // open the connection before using adapter
using (SqlDataAdapter adapter = new SqlDataAdapter("INPUT INTO Person", Connection))
{
// other stuff
}
}
// other stuff
}
或者将连接字符串作为方法参数传递:
private void AcceptData(string connectionString)
{
using (SqlConnection Connection = new SqlConnection(connectionString))
{
Connection.Open(); // open the connection before using adapter
using (SqlDataAdapter adapter = new SqlDataAdapter("INPUT INTO Person", Connection))
{
// other stuff
}
}
// other stuff
}
参考文献:
How to fix "The ConnectionString property has not been initialized"
C# Database The ConnectionString property has not been initialized