我目前正在構建一個程序,用於在用戶之間存儲數據庫中的消息,並在按下下面的按鈕時將這些消息返回給用戶。我正在使用一個使用OleDbConnection
和使用DataReader
的SQL CE數據庫。OleDbDataReader = null
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
說空內的微小變化的代碼,任何人都知道爲什麼嗎?
Btw所返回的值不爲null讀者本身爲空。 下面是非工作代碼。
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]);
}
}
有什麼異常嗎? – Szymon
發佈的代碼是工作代碼還是非工作代碼?一些觀察:1.學習參數化查詢以防止SQL注入。 2.如果試圖打開連接會引發異常,則需要退出該方法,因爲所有其他操作都會失敗。 3.在閱讀器上使用'use'塊或調用'Close()'。 – Tim
@Szymon是啊(解析查詢時出現錯誤[令牌行號,令牌行偏移量,令牌錯誤,,])但是,當while(reader.Read())行使用斷點時,我發現數據讀取器一片空白。 –