My application need to support multiple databases. Currently, it supports Postgres now I am adding support for Orcle and may be SqlServer in upcoming days.
Before asking any question lets look at codes.
IDbParser :
public interface IDbParser
{
IDbConnection GetDbConnection(string ServerName, string DbPortNumber, string Username, string Password, string DatabaseName);
IDbCommand GetDbCommand(string query, IDbConnection sqlConnection);
IDataParameter CreateParameter(string key, object value);
string GetDbQuery(DbQueries query);
}
OracleDbParser :
public class OracleParser : IDbParser
{
#region >>> Queries
private string SELECTGROUPSESSIONS = "....";
........
#endregion
public IDbCommand GetDbCommand(string query, IDbConnection sqlConnection)
{
var command = new OracleCommand();
command.CommandText = query;
command.Connection = (OracleConnection)sqlConnection;
command.CommandType = CommandType.Text;
command.CommandTimeout = 300;
return command;
}
public IDataParameter CreateParameter(string key, object value)
{
return new OracleParameter(key, value);
}
public IDbConnection GetDbConnection(string ServerName, string DbPortNumber, string Username, string Password, string DatabaseName)
{
connString = String.Format("Data Source=(DESCRIPTION = (ADDRESS_LIST = (ADDRESS=(PROTOCOL=TCP)(HOST={0})(PORT={1})))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME={2}))); Connection Timeout=60; User Id={3};Password={4};",
ServerName, DbPortNumber, DatabaseName, Username, Password);
return new OracleConnection(connString);
}
public string GetDbQuery(DbQueries query)
{
switch (query)
{
case DbQueries.SELECTGROUPSESSIONS:
return SELECTGROUPSESSIONS;
................
..............
default:
return String.Empty;
}
}
}
Similarly, there is parser for Postgres :
public class PostgresParser : IDbParser
{
#region >>> Queries
private string SELECTGROUPSESSIONS = "....";
........
#endregion
public IDbCommand GetDbCommand(string query, IDbConnection sqlConnection)
{
var command = new NpgsqlCommand();
command.CommandText = query;
command.Connection = (NpgsqlConnection)sqlConnection;
command.CommandType = CommandType.Text;
return command;
}
public IDataParameter CreateParameter(string key, object value)
{
return new NpgsqlParameter(key, value);
}
public IDbConnection GetDbConnection(string ServerName, string DbPortNumber, string Username, string Password, string DatabaseName)
{
string connString = String.Format("Server={0};Port={1};Timeout=60;CommandTimeout=300;" +
"User Id={2};Password={3};Database={4};",
ServerName, DbPortNumber, Username, Password, DatabaseName);
return new NpgsqlConnection(connString);
}
public string GetDbQuery(DbQueries query)
{
switch (query)
{
case DbQueries.SELECTGROUPSESSIONS:
return SELECTGROUPSESSIONS;
................
..............
default:
return String.Empty;
}
}
}
DatabaseParserFactory:
public class DatabaseParserFactory
{
public static IDbParser GetDbParser(string dbType)
{
CUCMDbType dbTypeName;
Enum.TryParse(dbType.ToLower(), out dbTypeName);
switch (dbTypeName)
{
case CUCMDbType.oracle:
return new OracleParser();
case CUCMDbType.postgres:
return new PostgresParser();
default:
return new PostgresParser();
}
}
}
Query execution :
public void Query(string queryStatement, DbParameterColl parameters, Action<IDataReader> processReader)
{
using (SqlConnection)
{
IDbCommand selectCommand = null;
selectCommand = _factory.GetDbCommand(queryStatement, SqlConnection);
selectCommand.Parameters.Clear();
using (selectCommand)
{
if (parameters != null)
{
foreach (var param in parameters)
{
selectCommand.Parameters.Add(_factory.CreateParameter(param.Key, param.Value));
}
}
try
{
using (var reader = selectCommand.ExecuteReader())
{
processReader(reader);
}
}
catch (Exception ex)
{
Logger.DebugFormat("Unable to execute the query. Query : {0} . Exception: {1}", queryStatement, ex);
Debug.WriteLine("\n\n>> Error on executing reader. Exception :\n " + ex);
}
}
}
}
FYI: There will only be SELECT queries and no other commands.
I am passing parameter's value as an object. Well, currently there is no problem assigning the parameters and executing the query. But in most of the blogs and in stackoverflow I could see that people have been suggesting to specify the Input direction, and most specifically Input type/DbType. Do I need to specify DbType ? Currently, my code runs fine with no errors. But I am afraid, it might break down in production.
Moreover I have no control over the type of parameter, it could be anything.
So what do you guys suggest? Or is there any better approach of doing this ?
First, you should take a look at DbProviderFactories - most of your code duplicates that already-existing standard functionality. Note that it is not yet available in .NET Core (but will be).
Regarding your question, in general you don't need to specify the parmeter direction - it's assumed to be the default. Database drivers can typically infer the database type from the CLR value you assign to a parameter, but it's a good idea to explicitly specify DbType just to be sure.
Related
In my DAO, I have:
public void UpdateProfile(string newName, string newBio, long profileId)
{
using var dbConnection = _databaseProvider.GetConnection();
dbConnection.SetQuery($"UPDATE `profile_data` SET `name` = #newName AND `bio` = #newBio AND `fixed_unicode` = 1 WHERE `profile_id` = #profileId");
dbConnection.AddParameter("newName", newName);
dbConnection.AddParameter("newBio", newBio);
dbConnection.AddParameter("profileId", profileId);
dbConnection.ExecuteQuery();
}
It results in:
Unhandled exception. MySql.Data.MySqlClient.MySqlException (0x80004005): Truncated incorrect DOUBLE value: 'hello.world'
I don't understand why, because the name column is a varchar(255), verified via:
>> SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'profile_data' AND COLUMN_NAME = 'name'
>> varchar
Below I will place code references in my main example, for anyone to check out if it helps debug the issue.
_databaseProvider:
public class DatabaseProvider : IDatabaseProvider
{
private readonly string _connectionString;
public DatabaseProvider(string connectionString)
{
_connectionString = connectionString;
}
public DatabaseConnection GetConnection()
{
var connection = new MySqlConnection(_connectionString);
var command = connection.CreateCommand();
return new DatabaseConnection(connection, command);
}
}
DatabaseConnection:
public class DatabaseConnection : IDisposable
{
private readonly MySqlConnection _connection;
private readonly MySqlCommand _command;
public DatabaseConnection(MySqlConnection connection, MySqlCommand command)
{
_connection = connection;
_command = command;
_connection.Open();
}
public void SetQuery(string commandText)
{
_command.Parameters.Clear();
_command.CommandText = commandText;
}
public int ExecuteQuery()
{
return _command.ExecuteNonQuery();
}
public Task ExecuteQueryAsync()
{
return _command.ExecuteNonQueryAsync();
}
public MySqlDataReader ExecuteReader()
{
return _command.ExecuteReader();
}
public object ExecuteScalar()
{
return _command.ExecuteScalar();
}
public int GetLastId()
{
SetQuery("SELECT LAST_INSERT_ID();");
return int.Parse(ExecuteScalar().ToString());
}
public void AddParameter(string name, object value)
{
_command.Parameters.AddWithValue(name, value);
}
public void Dispose()
{
_connection.Close();
_command.Dispose();
}
}
You UPDATE query is incorrect. Replace AND keyword with a comma.
The query should look like this:
$"UPDATE `profile_data` SET `name` = #newName,
`bio` = #newBio,
`fixed_unicode` = 1
WHERE `profile_id` = #profileId"
Without executing your code, I can notice that your UPDATE command is not correct.
Try this
UPDATE `profile_data` SET `name` = #newName ,`bio` = #newBio ,`fixed_unicode` = 1 WHERE `profile_id` = #profileId");
I am maintaining a previous developer work.
Here is the db layer class, it has .......
public class Database
{
private string mConnString;
private SqlConnection mConn;
private SqlDataAdapter mAdapter;
private SqlCommand mCmd;
private SqlTransaction mTransaction;
private bool disposed = false;
public Database() : this(Web.GetWebConfigValue("ConnectionString"))
{
}
public Database(string connString)
{
mConnString = connString;
mConn = new SqlConnection(mConnString);
mConn.Open();
mAdapter = new SqlDataAdapter();
mCmd = new SqlCommand();
mCmd.CommandType = CommandType.StoredProcedure;
mCmd.Connection = mConn;
}
public void CloseConnection()
{
mConn.Close();
}
public void BeginTransaction()
{
mTransaction = mConn.BeginTransaction();
mCmd.Transaction = mTransaction;
}
public void CommitTransaction()
{
mTransaction.Commit();
}
public void RollbackTransaction()
{
mTransaction.Rollback();
}
public void AddParam(string name, SqlDbType type, object value)
{
SqlParameter parameter = new SqlParameter('#' + name, type);
parameter.Value = value;
mCmd.Parameters.Add(parameter);
}
public void ChangeParam(string name, object value)
{
mCmd.Parameters['#' + name].Value = value;
}
public void DeleteParam(string name)
{
mCmd.Parameters.RemoveAt('#' + name);
}
public void AddReturnParam()
{
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "return";
parameter.Direction = ParameterDirection.ReturnValue;
mCmd.Parameters.Add(parameter);
}
public void AddOutputParam(string name, SqlDbType type, int size)
{
SqlParameter parameter = new SqlParameter('#' + name, type);
parameter.Direction = ParameterDirection.Output;
parameter.Size = size;
mCmd.Parameters.Add(parameter);
}
public int GetReturnParam()
{
return (int)mCmd.Parameters["return"].Value;
}
public object GetOutputParam(string name)
{
return mCmd.Parameters['#' + name].Value;
}
public void ClearParams()
{
mCmd.Parameters.Clear();
}
public void ExecNonQuery(string cmdText)
{
if(mConn.State==ConnectionState.Closed)
mConn.Open();
mCmd.CommandText = cmdText;
mCmd.ExecuteNonQuery();
}
public DataSet GetDataSet(string cmdText)
{
mCmd.CommandText = cmdText;
mAdapter.SelectCommand = mCmd;
DataSet ds = new DataSet();
mAdapter.Fill(ds);
return ds;
}
public IDataReader GetDataReader(string cmdText)
{
mCmd.CommandText = cmdText;
if(mConn.State==ConnectionState.Closed)
mConn.Open();
return mCmd.ExecuteReader(CommandBehavior.CloseConnection);
}
public DataTable GetDataTable(string cmdText)
{
return GetDataSet(cmdText).Tables[0];
}
public DataTable GetDataTable(string cmdText,string SQL)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = cmdText;
mAdapter.SelectCommand = cmd;
cmd.Connection = mConn;
DataSet ds = new DataSet();
mAdapter.Fill(ds);
return ds.Tables[0];
}
public DataRow GetDataRow(string cmdText)
{
DataTable dt = GetDataTable(cmdText);
DataRow dr;
if(dt.Rows.Count > 0)
dr = dt.Rows[0];
else
dr = null;
return dr;
}
public object GetScalar(string cmdText)
{
mCmd.CommandText = cmdText;
return mCmd.ExecuteScalar();
}
public void SetCommandType(CommandType type)
{
mCmd.CommandType = type;
}
~Database()
{
this.Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if(!this.disposed)
{
if(disposing)
{
if(mConn.State == ConnectionState.Open)
mConn.Close();
this.mCmd.Dispose();
this.mAdapter.Dispose();
this.mTransaction.Dispose();
}
}
disposed = true;
}
}
Can you help me in figuring out where connection might not be closed in all the cases where this class is being used.
The connection only ever gets closed when disposing the instance of the DataBase class.
However, while this class is implementing the disposable pattern, it doesn't implement the IDisposable interface - so you can't use it in a using statement.
Moreover, you have to rely on whoever is using this class to dispose it.
If they don't, the connection will not get closed until the Finalizer gets called, and that is completely out of the developer's control. It might even not get called at all - as the garbage collector might not need to clear memory during the runtime of whatever application is using this code.
This is why the proper way of handling connections to the database is as a local variable inside a using statement.
What you want to do is create the connection and open it as late as possible, and dispose it as soon as possible.
A proper method for handling calls to the database looks like this:
int ExecuteNonQuery(string sql)
{
using(var con = new SqlConnection(connectionString))
{
using(var cmd = new SqlCommand(sql, con))
{
con.Open();
return cmd.ExecueNonQuery();
}
}
}
Of course, you would want to add arguments to hold whatever parameters you'll need to pass to the database, and an argument to hold command type, but that should be built on the basis of this structure.
I have a project on GitHub called ADONETHelper (that I've been neglecting for the past year or so due to lack of spare time) that was written in order to reduce the code repetition when using ADO.Net directly.
I've written it a few years back so of course now I have improvements in mind but as I said, I don't have the spare time to work on it - but the general idea is still valid and useful.
Basically, it has a single Execute method that looks like this:
public T Execute<T>(string sql, CommandType commandType, Func<IDbCommand, T> function, params IDbDataParameter[] parameters)
{
using (var con = new TConnection())
{
con.ConnectionString = _ConnectionString;
using (var cmd = new TCommand())
{
cmd.CommandText = sql;
cmd.Connection = con;
cmd.CommandType = commandType;
if (parameters.Length > 0)
{
cmd.Parameters.AddRange(parameters);
}
con.Open();
return function(cmd);
}
}
}
Than I've added a few methods that use this method:
public int ExecuteNonQuery(string sql, CommandType commandType, params IDbDataParameter[] parameters)
{
return Execute<int>(sql, commandType, c => c.ExecuteNonQuery(), parameters);
}
public bool ExecuteReader(string sql, CommandType commandType, Func<IDataReader, bool> populate, params IDbDataParameter[] parameters)
{
return Execute<bool>(sql, commandType, c => populate(c.ExecuteReader()), parameters);
}
and so on.
Feel free to borrow ideas from that project - or even use it as is - I have a few applications using this and they run very well for quite some time now.
You aren't implementing the disposable pattern via the IDisposable interface, you just have a Dispose method, in turn you would not be able to call this in a using statement.
public class Database : IDisposable { ... }
This is all a bit suspect: I mean, if you are already using it you aren't using this in a using statement and trying to cache the connection seemingly. I would shy away from this altogether.
Also you have a Destructor, however its usage is wrong 99% of times.
While a persistence layer makes perfectly sense, you have to design it differently. What you do is pack some complexity into methods which still do the same, such as ChangeParam() or GetDataReader().
Normally, you have repositories which have knowledge about the underlying technicalities and remove that kind of complexity, such as GetAllCustomers() (with emphasis on the domain term customer).
When you have say 4 or 5 such repositories, then you start refactoring by abstracting complexity into a parent class. By doing so, you're packing the complexity such as in GetDataReader() and promote it from the repositories into an abstract repository that sits on top of it.
By starting from where you started you'll get just another layer which does not abstract nearly as much and has too much, often unnecessary, functionality.
If it were that easy, the ADO.NET API would already have it removed in the first place.
Another thing you should do is look at this simple but ever-recurring code snippet. It distillates some core concepts about IDisposable and using(){}. You'll always encounter it in correct code:
string sql = "SELECT * FROM t";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(sql, con))
{
SqlDataReader reader;
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
// TODO: consume data
}
reader.Close();
}
This is the stuff I'd expect to see in a persistence layer, and the consume data part is actually the most important, because it is domain-dependent. The rest is just boilerplate code with little interest.
Good day!
Using visual studio 2012, I have created a Student class with get and set codes, and i need to complete the StudentDAO class to create insert coding that will use to store data to database student table. this action is perform by a windows form button click event.
what i need to create a button click code and then insert into database code,
//Student.cs class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SRSJason
{
class Student
{
private string S_Student_id;
private string S_Full_name;
private DateTime S_Dob;
private string S_Address;
private int S_Contact;
private string S_Username;
private string S_Password;
public Student() //Default constructor
{
}
public Student(string Student_id, string Full_name, DateTime Dob, string Address, int Contact, string Username, string Password) //Overloadign
{
S_Student_id = Student_id;
S_Full_name = Full_name;
S_Dob = Dob;
S_Address = Address;
S_Contact = Contact;
S_Username = Username;
S_Password = Password;
}
public void setID(string Student_id)
{
S_Student_id = Student_id;
}
public string getID()
{
return S_Student_id;
}
public void setName(string Full_name)
{
S_Full_name = Full_name;
}
public string getName()
{
return S_Full_name;
}
public void setDob(DateTime Dob)
{
S_Dob = Dob;
}
public DateTime getDob()
{
return S_Dob;
}
public void setAddress(string Address)
{
S_Address = Address;
}
public string getAddress()
{
return S_Address;
}
public void setContact(int Contact)
{
S_Contact = Contact;
}
public int getContact()
{
return S_Contact;
}
public void setUsername(string Username)
{
S_Username = Username;
}
public string getUsername()
{
return S_Username;
}
public void setPassword(string Password)
{
S_Password = Password;
}
public string getPassword()
{
return S_Password;
}
}
}`
//StudentDAO class (please help me to complete this code)
`class StudentDAO
{
static string constring = "Data Source=JAZE;Initial Catalog=srsjason;Integrated Security=True";
SqlConnection m_con = new SqlConnection(constring);
}`
//button click from the form (please help me to complete this code as well)
private void submitstudent(object sender, EventArgs e)
{
}
please help me to complete this coding
First of all when you create private properties u cant access them in your forms, you have to create a method instead inside the same class then use it in your form. second you should know about the ORM - Object Relational Mapping that you are using.
Here I'll list them:
ADO.NET
LINQ to SQL
ADO.NET Entity Framework
When you picked one of those. next step would be learning about how they work and whats the syntax.
However knowing that you kinda showed a syntax of ADO.NET Here is an Example how you can insert the data in your data base using ADO.NET. If you want to add data directly from code-behind without a method. so basically on click event of your button.
private void btn_Click(object sender, EventArgs e)
{
try
{
//create object of Connection Class..................
SqlConnection con = new SqlConnection();
// Set Connection String property of Connection object..................
con.ConnectionString = "Data Source=KUSH-PC;Initial Catalog=test;Integrated Security=True";
// Open Connection..................
con.Open();
//Create object of Command Class................
SqlCommand cmd = new SqlCommand();
//set Connection Property of Command object.............
cmd.Connection = con;
//Set Command type of command object
//1.StoredProcedure
//2.TableDirect
//3.Text (By Default)
cmd.CommandType = CommandType.Text;
//Set Command text Property of command object.........
cmd.CommandText = "Insert into Registration (Username, password) values ('#user','#pass')";
//Assign values as `parameter`. It avoids `SQL Injection`
cmd.Parameters.AddWithValue("user", TextBox1.text);
cmd.Parameters.AddWithValue("pass", TextBox2.text);
//Execute command by calling following method................
//1.ExecuteNonQuery()
//This is used for insert,delete,update command...........
//2.ExecuteScalar()
//This returns a single value .........(used only for select command)
//3.ExecuteReader()
//Return one or more than one record.
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
Be sure that you've included your ConnectionString in your config file.
This question already has answers here:
Data Access Layer design patterns
(7 answers)
Closed 8 years ago.
I'm writing an 'off-the shelf' desktop app in C# that needs to connect to one of three different types of database (SQL Server, MySQL or SQL Server Compact) depending on the version and customer requirements.
I have been using ADO code as follows:
using (SqlConnection conn = MSSQLHelpers.GetConnection())
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM settings WHERE ID=#ID";
cmd.Parameters.AddWithValue("#ID", 1);
using (SqlDataReader rdr = MSSQLHelpers.GetDataReader(cmd))
{
if (rdr.Read())
{
Config.AdvancedSecurity = rdr.GetBoolean(rdr.GetOrdinal("advancedsecurity"));
Config.BookSampleInOnCreate = rdr.GetBoolean(rdr.GetOrdinal("newsamplein"));
etc....
}
rdr.Close();
}
}
conn.Close();
}
This is obviously specific to SQL Server. My question is what would be the best way to avoid repeating all the above for each of the three database types using MySqlConnection, SqlCeConnection etc?
Many thanks in advance for any help.
Jon
I have actually done similar, and I did with a hierarchy class structure using the INTERFACES. For example, if you look at SqlConnection, you be declared as inclusive of the "IDbConnection" interface. Likewise SqlCommand would include "IDbCommand", SqlDataAdapter uses "IDbDataAdapter" and similar for parameters and the like.
So, I had a parent class that was like a template that all would have (almost an abstract class), but since I had common stuff regardless of which connection type, it was actually a function class too.
public class MyDBHandler
{
public virtual IDbConnection GetConnection()
{ throw new Exception( "Please define specific GetConnection method"}; }
public virtual IDbCommand GetCommand()
{ throw new Exception( "Please define specific GetCommand method"}; }
public virtual IDbDataAdapter GetDataAdapter()
{ throw new Exception( "Please define specific DataAdapter method"}; }
public virtual string GetConnectionString()
{ throw new Exception( "Please define specific ConnectionString method"}; }
etc...
// Then some common properties you might want for connection path, server, user, pwd
protected string whatServer;
protected string whatPath;
protected string whatUser;
protected string whatPwd;
protected connectionHandle;
public MyDBHandler()
{
// always start with HAVING a connection object, regardless of actual connection or not.
connectionHandle = GetConnection();
}
// common function to try opening corresponding connection regardless of which server type
public bool TryConnect()
{
if( connectionHandle.State != System.Data.ConnectionState.Open )
try
{
connectionHandle.ConnectionString = GetConnectionString();
connectionHandle.Open();
}
catch( Exception ex )
{
// notify user or other handling
}
if( connectionHandle.State != System.Data.ConnectionState.Open )
MessageBox.Show( "Some message to user." );
// return true only if state is open
return connectionHandle.State == System.Data.ConnectionState.Open;
}
// Now, similar to try executing a command as long as it is of IDbCommand interface to work with
public bool TryExec( IDbCommand whatCmd, DataTable putResultsHere )
{
// if can't connect, get out
if( ! TryConnect() )
return false;
bool sqlCallOk = false;
if( putResultsHere == null )
putResultsHere = new DataTable();
try
{
da.Fill(oTblResults, putResultsHere);
// we got this far without problem, it was ok, regardless of actually returning valid data
sqlCallOk = true;
}
catch( Exception ex )
{
// Notify user of error
}
return sqlCallOk;
}
}
public class SQLHandler : MyDbHandler
{
public override IDbConnection GetConnection()
{ return (IDbConnection) new SqlConnection(); }
public override IDbCommand GetCommand()
{ return (IDbCommand) new SqlCommand("", connectionHandle ); }
public override IDbDataAdapter GetDataAdapter()
{ return (IDbDataAdapter) new SqlDataAdapter(); }
public override string GetConnectionString()
{ return "Driver={SQL Server}; blah, blah of properties"; }
}
public class MySQLHandler : MyDbHandler
{
public override IDbConnection GetConnection()
{ return (IDbConnection) new MySqlConnection(); }
public override IDbCommand GetCommand()
{ return (IDbCommand) new MySqlCommand("", connectionHandle ); }
public override IDbDataAdapter GetDataAdapter()
{ return (IDbDataAdapter) new MySqlDataAdapter(); }
public override string GetConnectionString()
{ return "Driver={MySql}; blah, blah of properties"; }
}
Then, in your code, depending on how you want to handle, you could do
MyDbHandler whichDatabase = new SQLHandler();
// set any settings for such connection and such...
IDbCommand cmd = whichDatabase.GetCommand();
cmd.CommandText = "select * from whereEver";
DataTable oTmp = new DataTable()
whichDatabase.TryExec( cmd, oTmp );
Now you have a table returned, and populated with rows/columns from the query as needed, close connection in the TryExec() call, or however you find fit.
Just an stripped-down version of something I did in the past.
If you want to swap between MySql, Sql-Server, Access, Visual FoxPro, etc create corresponding handlers.
I assigned the textbox inputs to getters and setters also created one connection class. How can I pass my getters and setters parameters to connection class so I can use it inside my mainform.
MemberClass
private string srDatabase = "";
private string srID = "";
private string srPass = "";
public string SDB
{
get
{
return srDatabase;
}
set
{
srDatabase= value;
}
}
public string SID
{
get
{
return srID ;
}
set
{
srID = value;
}
}
public string SPassword
{
get
{
return srPass ;
}
set
{
srPass = value;
}
}
ConnectionClass
class Connection
{
public static OracleConnection GetConnection(string dataSource, string userName, string password)
{
OracleConnection con = null;
if(!string.IsNullOrWhiteSpace(dataSource) && !string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
{
con = new OracleConnection("Data Source=" + dataSource + ";User Id=" + userName.ToUpper() + ";Password=" + password + ";");
return con;
}
return con;
}
}
MainForm
UserMembers = new UserMembers();
txtSrcUserDatabase.Text = src.srDatabase ;
txtSrcUserID.Text=src.srID.ToUpper();
txtSrcUserPassword.Text = src.srPass;
OracleConnection conn1 = Connection.GetConnection() // **here error**
conn1.Open();
using (OracleCommand Names = new OracleCommand("SELECT TABLE_NAME FROM USER_TABLES ORDER BY TABLE_NAME", conn1))
{
using (OracleDataReader reader = Names.ExecuteReader())
{
while (reader.Read())
{
//Do something
}
}
}
Your method GetConnection requires three parameters. You need to pass them to the method.
UserMembers src = new UserMembers();
src.srDatabase =txtSrcUserDatabase.Text;
src.srID = txtSrcUserID.Text.ToUpper();
src.srPass = txtSrcUserPassword.Text;
OracleConnection conn1 = Connection.GetConnection(src.srDatabase, src.srID, src.srPass)
conn1.Open();
......
Or you could pass the instance of UserMembers to the GetConnection method creating an overload of GetConnection like this
class Connection
{
// the first overload that takes 3 string parameters
public static OracleConnection GetConnection(string dataSource, string userName, string password)
{
....
}
// The second overload that takes an instance of UserMembers
public static OracleConnection GetConnection(UserMembers src )
{
OracleConnection con = null;
if(!string.IsNullOrWhiteSpace(sr.srDatabase) && !string.IsNullOrWhiteSpace(sr.srID) && !string.IsNullOrWhiteSpace(sr.srPass))
{
con = new OracleConnection("Data Source=" + sr.srDatabase + ";User Id=" + sr.srID.ToUpper() + ";Password=" + sr.Pass + ";");
}
return con;
}
}
As a side note. If you need the srID member to be always in upper case then move this logic in the setter property, and you could stop to worry about the proper formatting of this member when you try to read it back
public string SID
{
get { return srID ; }
set { srID = value.ToUpper(); }
}