OleDbConnection baglanti =
new OleDbConnection("connect");
OleDbCommand komut = new OleDbCommand();
OleDbDataReader dr;
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if(textBox1.Text=="" || textBox2.Text=="" || textBox3.Text=="" || maskedTextBox1.Text=="" || dateTimePicker1.Text=="" || maskedTextBox2.Text=="" || textBox6.Text=="")
{
MessageBox.Show("Lütfen Boş alanları doldurunuz !!");
}
else
{
baglanti.Open();
komut.Connection = baglanti;
komut.CommandText=("Select TcKimlik from Hasta");
dr = komut.ExecuteReader();
while(dr.Read())
{
if(dr["TcKimlik"].ToString()==textBox1.Text.ToString())
{
MessageBox.Show("aaaaa");
}
else
{
komut.CommandText = ("insert into Hasta (TcKimlik,h_adı,h_soyadı,tel_no,ran_tar,ran_saati,sikayet_nedeni) values('" + textBox1.Text.ToString() + "','" + textBox2.Text.ToString() + "','" + textBox3.Text.ToString() + "','" + maskedTextBox1.Text.ToString() + "','" + dateTimePicker1.Text.ToString() + "','" + maskedTextBox2.Text.ToString() + "','" + textBox6.Text.ToString() + "')");
komut.ExecuteNonQuery();
MessageBox.Show("Kayıt Başarı İle Tamamlandı", "Kayıt Başarılı", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
baglanti.Close();
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
maskedTextBox1.Clear();
maskedTextBox2.Clear();
textBox6.Clear();
}
}
我尝试了很多方法,但我无法找到解决方案。如果我在注册数据之前检查数据或生成dr.Close()
,我可以保存数据,但之后出现错误,因为我过早地关闭了数据读取器。
我想检查数据库中的数据,但是我收到如下错误。
与此命令相关联,已经有一个应该首先关闭的显式DataReader。
答案 0 :(得分:1)
您的代码问题是您正在利用Command
对象一次执行reading and inserting
条记录。
您需要逐个执行操作,不能同时执行这两项操作。所以你的代码应该是这样的
using (OleDbconnection connection = new OleDbconnection (ConnectionString))
{
connection.Open();
OleDbCommand select = new OleDbCommand("..selecte query",connection);
OleDbDataReader reader = select.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
//read data you want
//you might not need another connection , but i added to seperate it , you can reuse connection you created and perfrom update
using(OleDbconnection connection1 = new OleDbconnection (ConnectionString))
{
OleDbCommand insert= new OleDbCommand ("..insertquery", connection1);
insert.ExecuteNonQuery();
}
}
}
reader.Close();
}
}
你可以使用命令对象来执行多个任务,但它应该是一个一个,例如
//first complete reading and close reader
//second do insert operation complete it
//third do update operation
还有一个建议使用Parameter
,因为您的插入查询是针对 sql injection 攻击打开的,如果您使用参数化查询可以解决该问题