我尝试从数据库中收到用户的昵称,但它总是返回分配给字符串昵称变量的值。
public string GetEigenaarBlog(int gebruikerid)
{
string nickname = null;
try
{
connection.Open();
string sql = "SELECT Nickname FROM Gebruiker WHERE GebruikerID = :gebruikerid";
command = new OracleCommand(sql, connection);
command.Parameters.Add(new OracleParameter("gebruikerid", gebruikerid));
nickname = Convert.ToString(command.ExecuteReader());
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
connection.Close();
}
return nickname;
}
这是我的代码:
private void listBoxBerichten_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox lb = (ListBox)sender;
Blog blog = (Blog)lb.Items[lb.SelectedIndex];
int blogid = blog.BlogID;
geselecteerdeBlog = dk.GetGeselecteerdeBlog(blogid);
string blogeigenaar;
foreach (Blog b in geselecteerdeBlog)
{
blogeigenaar = dk.GetEigenaarBlog(b.GebruikerID); //This is the method where is the problem
tbGeblogd.Text = Convert.ToString(b.Datum);
tbTitel.Text = b.Titel;
tbDoor.Text = blogeigenaar;
tbBlogInhoud.Text = b.Inhoud;
}
}
参数有效,它从表单中读取该参数。
当我将string nickname = null
更改为string nickname = 'hello'
时,它会将昵称返回为hello。所以它返回指定的值。当我保留string nickname = null
然后它返回null
我做错了什么? SQL查询是正确的,用户存在于数据库中。我没有收到任何错误或警告。
谢谢!
答案 0 :(得分:4)
您的代码需要以这种方式更改
public string GetEigenaarBlog(int gebruikerid)
{
string nickname = null;
try
{
connection.Open();
string sql = "SELECT Nickname FROM Gebruiker WHERE GebruikerID = :gebruikerid";
command = new OracleCommand(sql, connection);
command.Parameters.Add(new OracleParameter("gebruikerid", gebruikerid));
OracleDataReader reader = command.ExecuteReader();
// Now try to read from the reader (and position the reader on the first record returned)
if(reader.Read())
nickname = reader[0].ToString();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
connection.Close();
}
return nickname;
ExecuteReader方法返回一个OracleDataReader,在尝试从中读取之前,需要将该对象放在第一个记录上。因此,您需要调用Read方法,如果该方法返回true,则可以读取字符串。
然而,如果你有一个只返回一行和一列的查询,那么一个非常快速的方法是通过ExecuteScalar方法
connection.Open();
string sql = "SELECT Nickname FROM Gebruiker WHERE GebruikerID = :gebruikerid";
command = new OracleCommand(sql, connection);
command.Parameters.Add(new OracleParameter("gebruikerid", gebruikerid));
// ExecuteScalar returns the value of the first row/first column, or null if
// there is no record to return. Need to be carefull here
object result = command.ExecuteScalar();
if(result != null)
nickname = result.ToString();
作为旁注,我看不到完整的代码,但似乎你保留了一个全局连接对象 这被认为是一种糟糕且不必要的做法,因为Connection Pooling mechanism可以做更好的工作来保持连接对象的可用性
答案 1 :(得分:1)
您无法以这种方式访问datareader。您必须遍历datareader并获取数据。有关详细信息,请参阅http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oracledatareader.aspx。
而不是
nickname = Convert.ToString(command.ExecuteReader());
试试这个
OracleDataReader reader = command.ExecuteReader();
nickname = "";
while (reader.Read())
{
nickname = Convert.ToString(reader[0]));
}