我是C#的新手,我已将其与Oracle11g连接并使用Visual Studio 2013作为工具。我试图显示一个名字'查询返回到文本框但它既不显示错误消息也不显示输出。请帮我解决这个问题。谢谢......这是我的代码..
private void button1_Click(object sender, EventArgs e)
{
try
{
string oradb = "Data Source=ORCL;User Id=hr; Password=123;";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select name from std where cgpa=2.82;";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
textBox1.Text = dr.GetString(0);
conn.Dispose();
}
catch (Exception ex) { MessageBox.Show("\n"+ex); }
}
答案 0 :(得分:1)
数组索引从索引0开始,而不是1.返回的字符串(如果有)位于
textBox1.Text = dr.GetString(0);
编写代码的更正确的方法如下
private void button1_Click(object sender, EventArgs e)
{
try
{
string oradb = "Data Source=ORCL;User Id=hr; Password=123;";
// Use the using statements around disposable objects....
using(OracleConnection conn = new OracleConnection(oradb))
using(OracleCommand cmd = new OracleCommand())
{
conn.Open();
// These two parameters could be passed directly in the
// OracleCommand constructor....
cmd.Connection = conn;
cmd.CommandText = "select name from std where cgpa=2.82;";
// Again using statement around disposable objects
using(OracleDataReader dr = cmd.ExecuteReader())
{
// Check if you have a record or not
if(dr.Read())
textBox1.Text = dr.GetString(0);
}
}
}
catch (Exception ex) { MessageBox.Show("\n"+ex); }
}
如果您的代码只能返回一个包含单个列的记录,那么您可以使用性能更高的ExecuteScalar而无需构建OracleDataReader
// Again using statement around disposable objects
object result = cmd.ExecuteScalar();
if(result != null)
textBox1.Text = result.ToString();