【发布时间】:2018-04-26 20:43:29
【问题描述】:
我目前正在构建一个程序,它将用户之间的消息存储在数据库中,并在按下下面的按钮时将这些消息返回给用户。我正在使用使用OleDbConnection 和DataReader 的SQL CE 数据库。
private void button3_Click(object sender, EventArgs e)
{
string [] lec_name = new string [10] ;
string [] content = new string [10] ;
string conn = "Provider=Microsoft.SQLSERVER.CE.OLEDB.3.5;Data Source=C:\\Users\\Leon\\Admin.sdf";
OleDbConnection connection = new OleDbConnection(conn);
OleDbCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM Contact_DB WHERE Student_ID =" + iD + " AND Direction = '" + "To the student" + "'";
try
{
connection.Open();
}
catch (Exception ex)
{
MessageBox.Show("" + ex.Message);
}
OleDbDataReader reader = command.ExecuteReader();
int up = 0;
int count = 0;
while (reader.Read())
{
lec_name[up] = reader["Lecturer_Name"].ToString();
content[up] = reader["Description"].ToString();
up++;
MessageBox.Show("The lecturer " + lec_name[count] + " has messaged you saying :" + "\n" + content[count]);
count++;
}
}
此代码适用于我的 Student 类,但是当我在 Lecturer 类中重用代码并进行细微更改时,OledbDataReader 显示为空,有人知道为什么吗?
顺便说一句,返回的值不为空,阅读器本身为空。
下面是无效的代码。
private void button2_Click(object sender, EventArgs e)
{
string [] studentID = new string [10] ;
string [] content = new string [10] ;
string conn = "Provider=Microsoft.SQLSERVER.CE.OLEDB.3.5;Data Source=C:\\Users\\Leon\\Admin.sdf";
OleDbConnection connection = new OleDbConnection(conn);
OleDbCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM Contact_DB WHERE Lecturer_Name =" + full + " AND Direction = '" + "To the lecturer" + "'";
try
{
connection.Open();
}
catch (Exception ex)
{
MessageBox.Show("" + ex.Message);
}
OleDbDataReader reader1 = command.ExecuteReader();
int up = 0;
int count = 0;
while (reader1.Read())
{
studentID[up] = reader1["Student_ID"].ToString();
content[up] = reader1["Description"].ToString();
up++;
}
MessageBox.Show("The student " + studentID[count] + " has messaged you saying :" + "\n" +content[count]);
}
}
【问题讨论】:
-
有异常吗?
-
发布的代码是工作代码还是非工作代码?几点观察: 1. 学习参数化查询以防止 SQL 注入。 2. 如果尝试打开连接抛出异常,则需要退出该方法,因为其他所有操作也会失败。 3. 在阅读器上使用
using块或调用Close()。 -
@Szymon 是的(解析查询时出错。[Token line number,Token line offset,,Token in error,,])但是当在 while 上使用断点时(reader.Read() ) 行我发现 datareader 为空。
-
学生和讲座都在 Contact_DB 表中?还要检查“WHERE Student_ID”子句是否正确。
-
不应该引用讲师的名字吗?即
SELECT * FROM Contact_DB WHERE Lecturer_Name ='" + full + "' AND Direction = '" + "To the lecturer" + "'"?
标签: c# null oledbdatareader