我已经在一个表单(Form1)中创建了一个oracle数据库连接,并以另一种形式(Form2)使用相同的连接从数据库中检索一些数据!。但是当我尝试将数据检索到一个数据时,我得到一个错误未处理的异常第二种形式的标签!
form1的代码如下(工作正常!)
public void connection()
{
con = new OracleConnection("Data Source = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST ="+ip.Text+")(PORT ="+port.Text+"))) " +
" (CONNECT_DATA = (SERVER = SHARED) (SERVICE_NAME = ora12c) )" +
" ); User Id =" + uname.Text + "; password=" + pword.Text);
}
private void button1_Click(object sender, EventArgs e)
{
connection();
con.Open();
Form2 f2 = new Form2();
f2.Show();
}
第二种形式的代码2
private void button1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
f1.connection();
f1.con.Open();
OracleCommand cmd = new OracleCommand();
cmd.CommandText = "Select name from username";
cmd.Connection = f1.con;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
label1.Text = dr.GetString(0);
}
当我输入详细信息(用户名,密码等)并单击form1中的lgin按钮时,我可以访问form2,但是当我单击加载按钮时,我会在form2中找到错误
"An unhandled exception of type 'Oracle.DataAccess.Client.OracleException' occurred in Oracle.DataAccess.dll"
突出显示f1.con.Open();
答案 0 :(得分:0)
您正在Form1
Form2 button1_Click1 of
f1.connection1 . Due to this the connection string in
Form1`中创建is generated using blank values of the text boxes of
的新实例。
要解决此问题,您需要确保在Form1.connection
方法中创建的连接应存储在某处,以便您也可以在Form2
中使用相同的连接。
考虑使用一个辅助类,它将连接对象维护为其中的静态对象。您可以在一个地方设置并在其他地方检索它。
public static class DatabaseHelper
{
private static OracleConnection oracleConnection;
private static string connectionStringTemplate = "Data Source = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST ={0})(PORT ={1}))) (CONNECT_DATA = (SERVER = SHARED) (SERVICE_NAME = ora12c) ) ); User Id ={2}; password={3}";
public static void SetConnection(string ipAddress, string portNumber, string userName, string password)
{
var connectionString = string.Format(connectionStringTemplate, ipAddress, portNumber, userName, password);
oracleConnection = new OracleConnection(connectionString);
}
public static void SetConnection(string connectionString)
{
oracleConnection = new OracleConnection(connectionString);
}
public static OracleConnection GetConnection()
{
return oracleConnection;
}
}
现在,您可以使用DatabaseHelper.SetConnection
中的Form1
方法来设置连接。
private void button1_Click(object sender, EventArgs e)
{
DatabaseHelper.SetConnection(ip.Text,port.Text, uname.Text, pword.Text);
Form2 f2 = new Form2();
f2.Show();
}
并检索并重用Form2中的连接,如下所示。
private void button1_Click(object sender, EventArgs e)
{
OracleConnection con = DatabaseHelper.GetConnection();
OracleCommand cmd = new OracleCommand();
cmd.CommandText = "Select name from username";
cmd.Connection = con;
con.Open();
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
label1.Text = dr.GetString(0);
}
这可以帮助您解决问题。