我在C#中创建了一个程序,它将数据插入到Oracle数据库中。这是非常程序化的,我想改进我的程序(和我的知识)来使用类。我在调用带参数的方法时遇到了一些麻烦。这是我的代码:
public class Oracle {
public void Insert() {
string oracleConnectionString = "User Id=" + l_orauser + "; Password=" + l_orapass + "; Data Source=" + l_oradb;
using (OracleConnection oracleConnection = new OracleConnection(oracleConnectionString)) {
oracleConnection.Open();
OracleGlobalization oracleSession = oracleConnection.GetSessionInfo();
oracleSession.DateFormat = "dd-mm-yyyy hh24:mi:ss";
oracleConnection.SetSessionInfo(oracleSession);
OracleTransaction oracleTransaction = oracleConnection.BeginTransaction();
OracleCommand oracleCommand = oracleConnection.CreateCommand();
oracleCommand.Transaction = oracleTransaction;
oracleCommand.CommandType = CommandType.Text;
string oracleCommandText = "insert into T1 (C1, C2, C3) values (:l_c1, :l_c2, :l_c3)";
oracleCommand.CommandText = oracleCommandText;
oracleCommand.BindByName = true;
oracleCommand.Parameters.Add("l_c1", OracleDbType.Byte, 3).Value = l_c1;
oracleCommand.Parameters.Add("l_c2", OracleDbType.Date).Value = l_c2;
oracleCommand.Parameters.Add("l_c3", OracleDbType.Varchar2, 1024).Value = l_c3;
try {
oracleCommand.ExecuteNonQuery();
oracleTransaction.Commit();
}
catch (Exception ex) {
oracleTransaction.Rollback();
MessageBox.Show(ex.Message);
}
finally {
oracleCommand.Parameters.Clear();
oracleCommand.Dispose();
oracleTransaction.Dispose();
oracleConnection.Close();
oracleConnection.Dispose();
}
}
}
}
我想用一些参数来调用它 - 变量:l_orauser,l_orapass,l_oradb,l_c1,l_c2,l_c3,它们取自表单的元素,例如textbox,datetimepicker。我怎么能这样做?
public static void Main(string[] args) {
var testOracle = new Oracle();
testOracle.Insert();
}
答案 0 :(得分:-1)
作为参考,我添加了代码,也许有人会发现它很有用:
public static void Main(string[] args) {
string oracleUser, oraclePassword, oracleDatabase;
List<string> oracleArguments = new List<string>();
//0 = oracleUser
//1 = oraclePassword
//2 = oracleDatabase
//3 = oracleCommandText
//4+ = oracleCommand.Parameters
l_orauser = "schema1";
l_orapass = "schema1pass";
l_oradb = "db1";
oracleArguments.Add(l_orauser);
oracleArguments.Add(l_orapass);
oracleArguments.Add(l_oradb);
Oracle testOracle = new Oracle();
testOracle.Insert(oracleArguments);
}
Oracle课程:
public class Oracle {
public void Insert(List<string> oracleArguments) {
string oracleConnectionString = "User Id=" + oracleArguments[0] + "; Password=" + oracleArguments[1] + "; Data Source=" + oracleArguments[2];
using (OracleConnection oracleConnection = new OracleConnection(oracleConnectionString)) {
//do something
}
}
}