我正在尝试连接到我们的数据库并创建一个程序,该程序从表中读取并将信息发送到文本框/标签。我收到一个错误:
int numberOfRowsFeched = oleDbDataAdapter1.Fill(dataSet1, "Böcker");
错误:InvalidOperationException
private void btn1_Click(object sender, EventArgs e)
{
{
string sqlQuery = "SELECT Fält2, Fält3 FROM Böcker WHERE Fält2 = " + "'\\" + txt1.Text + "\\'";
oleDbDataAdapter1.SelectCommand.CommandText = sqlQuery;
dataSet1.Clear();
oleDbConnection1.Open();
int numberOfRowsFeched = oleDbDataAdapter1.Fill(dataSet1, "Böcker");
if (numberOfRowsFeched > 0)
{
DataTable dt = dataSet1.Tables["Böcker"];
lbl1.Text = dt.Rows[0][0].ToString() + " " +
dt.Rows[0][1].ToString();
lbl2.Text = dt.Rows[0][2].ToString();
}
else
{
lbl1.Text = "Boken hittades inte.";
lbl1.Text = "";
}
}
}
}
我正在使用的新代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.OleDb;
using System.Data.SqlClient;
namespace MySQL
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btn1_Click(object sender, EventArgs e)
{
string ConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\cetin.cigel\\databasbibliotek.mdb;User Id=admin;Password=;";
string SqlString = "SELECT Fält1, Fält2, Fält3 FROM Böcker WHERE Fält2 = ?";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbDataAdapter da = new OleDbDataAdapter(SqlString, conn))
{
da.SelectCommand.Parameters.AddWithValue("Fält2", txt1.Text);
DataTable dt = dataSet1.Tables["Böcker"];
da.Fill(dt);
if (dt.Rows.Count > 0)
{
string text = string.Format("{0} {1}",
dt.Rows[0].Field<string>(0),
dt.Rows[0].Field<string>(1));
lbl1.Text = text;
lbl2.Text = dt.Rows[0].Field<string>(2);
}
else
{
lbl1.Text = "Boken hittades inte.";
}
}
}
}
}
}