I had small c# software that works on several database on several servers and I need to switch between different schema so..
depending on the current server ip I connect to master table on specified server
and get the schema name then add as variable within the connection string by this way ..
is it safe to use this way to make connection string flexible ?
if no then what do you suggest
string oradb = "Data Source=source;User Id=" + DBSchema + ";Password=pwd;";
In general run-time parameters are to be stored outside your code and in many cases the config file is one of the best places for that. You could use a factory method to build the connection string as in CodeProject-Don't Hard Code Your Data Providers or you could write a few lines of code to set the values using the .NET connection string builder as in ConnectionStringBuilder Class.
for example currently I have a web application that 2 web forms that need 2 different connection I will show you how I have it for 1 of the 2 forms
public static string storedProcName = "NameOfSomeStoredProc";
public string ConnString
{
get { return ConfigurationManager.ConnectionStrings["DbConn2"].ConnectionString; }
}
public string UserConnName
{
get { return string.Concat(ConfigurationManager.AppSettings["userConnName"], storedProcName); }
}
the method actual stored procedure call inside a method will look like the following I am passing in the Stored Proc name based on a static storedProcName declared above..
Create yourself a Helper Class and you can have something like the following that you would call from within your Class where you are wanting to execute the code
HelperClass.cs
public static DataSet ExecuteDataSet2(string sql, CommandType cmdType, params OracleParameter[] parameters)
{
using (DataSet ds = new DataSet())
using (OracleConnection connStr = new OracleConnection(ConfigurationManager.ConnectionStrings["DbConn2"].ConnectionString))
using (OracleCommand cmd = new OracleCommand(sql, connStr))
{
cmd.CommandType = cmdType;
cmd.CommandTimeout = 60 * 22;
foreach (var item in parameters)
{
cmd.Parameters.Add(item);
}
try
{
cmd.Connection.Open();
new OracleDataAdapter(cmd).Fill(ds);
}
catch (Exception ex)
{
utilities.SendErrorEmails(ex);
throw ex;
}
return ds;
}
}
Your Web.Config for example would look like this if you have 2 different DB connection string.. you would create the same method as above calling it ExecuteDataSet1.... and change the DbConn2 to DbConn and in the Public string ConnString change the DbConn2 to DbConn in your other class or have a check box and depending on the selection you can store botn ConnString get retrun .. calling your other one ConnString2 pretty straight forward
<connectionStrings>
<add name="DbConn" connectionString="Data Source={0};User Id={1};Password={2};" />
<add name="DbConn2" connectionString="Data Source={0};User Id={1};Password={2};" />
</connectionStrings>
<appSettings>
<add key="userConnName" value="NameOfOracleUser." />
</appSettings>
//Pay close attention to the . in the NameOfOracleUser., this depending how you have your procedures setup you would have OracleDbUserName.StoredProcedure name to execute.. notice in the Populate_DataGrin method I am passing the UserConnName and the string.Concat will pick up the storedProcName from this
public static string storedProcName = "NameOfSomeStoredProc"; works like a charm and if you had a dropdown of stored proc names to run.. it would work the same by assigning the name based on the drowpdown selection text..
last but not least the method / event that calls the ExecuteDataSet2 would look like this
private void Populate_DataGrin(int intMonth, string strLocation)
{
dtSomeDataTable = OracleDBHelper.ExecuteDataSet2(UserConnName, CommandType.StoredProcedure
, new OracleParameter("var_IntMonth", intMonth)
, new OracleParameter("var_StrLocation", strLocation)
, new OracleParameter
{
ParameterName = "p_cursor"
,
OracleDbType = OracleDbType.RefCursor
,
Direction = ParameterDirection.Output
}
).Tables[0];
YourDataGrid.DataSource = null;
YourDataGrid.DataSource = dtSomeDataTable;
YourDataGrid.DataBind();
}
Related
I have created a class for the MS Access database connection. It works fine on the majority of the forms within my Winforms app. However, I have a form where the user can add, edit or delete information from the database. I've constructed that part using a string, but when I remove the long database connection string I had there before and replace it with the class I created it throws an exception.
I've tried changing the code by removing the string, but I want to use the string method.
This is the code I have for the delete button click event
string con = (#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source =C:\Users\folder\Desktop\ApplicationFolder\AppName\bin\Debug\DataBase\DatabaseName.accdb");
string Query = "delete from Employees2 where EmployeeName = '" +
this.txtAdminFEmployee.Text + "' ; ";
OleDbConnection ConnectionString = new OleDbConnection(con);
OleDbCommand command = new OleDbCommand(Query, ConnectionString);
OleDbDataReader reader;
try
{
ConnectionString.Open();
reader = command.ExecuteReader();
DialogResult result = MessageBox.Show("Employee Deleted Successfully",
"Information",
MessageBoxButtons.OK, MessageBoxIcon.Information);
while (reader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
ConnectionString.Close();
This is the database class I created
using System.Data.OleDb;
namespace AppName
{
class OledbConnect
{
public OleDbConnection con;
public void Connection()
{
con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\DatabaseName.accdb");
}
}
}
I need to know how to use the database class in that string. I've tried different ways but nothing works. I am still new to c# and Google is not really returning anything I can use. Thanks
Your initial code works, but confusion is evident in the naming of variables.
string con = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source =C:\Users\folder\Desktop\ApplicationFolder\AppName\bin\Debug\DataBase\DatabaseName.accdb";
(I've taken the un-needed parentheses off the declaration; it's just a string.)
Calling that string 'con' is a bit confusing. I'd call it 'connectionString', or maybe 'cs' for short.
OleDbConnection ConnectionString = new OleDbConnection(con);
OleDbCommand command = new OleDbCommand(Query, ConnectionString);
OK, so you correctly create an OleDbConnection, passing the connection string (con) to its constructor. This is good. But you confusingly call it ConnectionString. It isn't the connection string; it's the connection, and your code thereafter uses it correctly.
So that works. Confusing for a human to read because of the mis-naming of variables, but the compiler doesn't care what their names are - it knows very well that ConectionString is an OleDbConnection and doesn't feel any of the cognitive dissonance that I do when I look at it.
If you rename the variables in the original code as I've suggested, and then copy that code into your class (BTW, I'd just call it DbConnection; it's current name is very close to another class name which might also be confusing), paying attention to what each statement does and what each variable represents then you should be good to go.
This is a noob question but I have been stuck here for a few hours so I need to get passed this. I have this Windows App that performs a simple function. It makes a trip to the DB and checks if a specific record exists and if it does then perform some operation. However it just doesn't want to read the connection string - it comes as null all the time. I keep getting null every time I initialize my connection string. What could I be doing wrong. I only have one connection string named App.config.
Class File:
private class ClassA
{
private string myConnectionString = "";
private SqlConnection mySQLConnection;
private SqlCommand mySQLCommand;
private int CheckIfSerialNumberExists(UInt64 ColumnToCheck)
{
int countResult = 0;
myConnectionString = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString; //I get an object reference null here when the compiler executes this line. I have been using this structure for years and never got any issues
using (mySQLConnection = new SqlConnection(myConnectionString))
{
string procName = "SELECT Count(*) ColumnName FROM Table WHERE ColumnName='" + ColumnToCheck + "'";
mySQLCommand = new SqlCommand(procName, mySQLConnection);
mySQLConnection.Open();
countResult = (int)mySQLCommand.ExecuteScalar();
}
return countResult;
}
private void someFunc()
{
//Test value: 5
if(CheckIfSerialNumberExists(5) > 0)
{
//Don't do anything
}
else
{
//Save to DB
}
}
}
Config File:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="ConnectionStringName"
connectionString="Data Source=ServerName;Initial Catalog=DatabaseName;Persist Security Info=True;User ID=**;Password=****"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1"/></startup>
</configuration>
So here is the quick fix:
In my windows app I am referencing a class library project. I had only added the connection string in that project. I added it to my windows app project and there we go, all was working. Really feel like an idiot.
In window application, i am trying to work with database, how to write connection string in app.config. The below is connection string in app.config
<configuration>
<appSettings >
<add key ="mycon"
value ="server=192*****;database=*****;
uid=**;pwd=*****;"/>
</appSettings>
</configuration>
Code to connect database:
SqlConnection con = new SqlConnection(
ConfigurationSettings.AppSettings["mycon"].ToString()); con.Open();
SqlCommand cmd = new SqlCommand("Usp_chat_login", con);
cmd.CommandType = CommandType.StoredProcedure ;
cmd.Parameters.Add("#userid", SqlDbType.VarChar, 20);
cmd.Parameters["#userid"].Value = textBox1.Text;
cmd.Parameters.Add("#password", SqlDbType.VarChar, 20);
cmd.Parameters["#password"].Value = textBox2.Text;
int reslt = cmd.ExecuteNonQuery(); con.Close();
if (reslt > 0)
{
MessageBox.Show("Yes");
}
else
{
MessageBox.Show("No");
}
Every time i am getting reslt=-1, even if i pass correct credentials
Every time i am getting reslt=-1, even if i pass correct credentials
This has nothing to do with the credentials, nor does it pertain to the config file. If authentication/authorization to the database failed, an exception would be thrown.
The problem is likely in your Usp_chat_login procedure.
See the documentation for ExecuteNonQuery():
For UPDATE, INSERT, and DELETE statements, the return value is the
number of rows affected by the command. When a trigger exists on a
table being inserted or updated, the return value includes the number
of rows affected by both the insert or update operation and the number
of rows affected by the trigger or triggers. For all other types of
statements, the return value is -1. If a rollback occurs, the return
value is also -1.
Other notes:
Types which implement IDisposable should be disposed of, especially types which interact with unmanaged resources (e.g. database connections). A simple way to do this is to wrap the instances of these types in a using statement.
Plain-text passwords are considered insecure/irresponsible in any application.
Write it in App.XAML
public partial class App : Application
{
public App()
{
string connectionStr = "Data Source=system\\SQLExpress;Initial Catalog=DBName; user id=sa; password=test123;";
Application.Current.Properties["conStr"] = connectionStr;
}
}
and Access it in main form
static string strCon = Application.Current.Properties["conStr"].ToString();
Does anyone know how can I central the db connection in c# .net (perhaps in the mian.master)?
I have the following code for the db connection and used to call to the difference stored proc to retrieved data.
string strConnString = ConfigurationManager.ConnectionStrings["testString"].ConnectionString;
SqlConnection mySqlConnection = new SqlConnection(strConnString);
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText = "EXEC app_campaign_select #CampaignID=" + Request.QueryString["ixCampaign"].ToString();
mySqlConnection.Open();
SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
Instead of coding it in every pages and connection to the db multiple times, any way I can code the following connection code in the master page and only connecting to the db once, then each page can call it when need to be connect into the db
string strConnString = ConfigurationManager.ConnectionStrings["testString"].ConnectionString;
SqlConnection mySqlConnection = new SqlConnection(strConnString);
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
SqlDataReader mySqlDataReader;
Add it to a static DAL class and add parameters as needed.
public static void YourFunction() {
// your code
}
Note:
Beware this line: mySqlCommand.CommandText = "EXEC app_campaign_select #CampaignID=" + Request.QueryString["ixCampaign"].ToString();
If that QueryString comes from a user entered value somewhere, you could be open to SQL Injection.
Sure. Just create a helper class that has a few static methods in them for each type of return type you could have. Pass to one a string for stored procedure name and have an overloaded one that takes a string for a sql statment that you would pass in. You can also have one that just returns back a scalar value as well. So you would probably have 3 or so static methods you could call from any page.
The connection name 'MySqlServer' was not found in the applications configuration or the connection string is empty.
So, I have a page with a panel that will display when the connection in the web config is found and the connection is valid; using a try/catch as long as the add name"VALUE" is in the config connection strings if the server data is bad the page will load and the panel is set to invisible... I need to be able to handle the following...
If the named value in this case MySqlServer is used in the aspx; aspx.cs but not found in the config I do not want the error to occur; connection name was not found.... I just want to not show the panel like when the SqlConnection.Open fails when the name is found but data is bad...
aspx
<asp:SqlDataSource runat="server" ID="allowedIPsSqlDataSource"
ConnectionString="<%$ ConnectionStrings:MySqlServer %>"
aspx.cs
string connectionString = ConfigurationManager.ConnectionStrings["MySqlServer"].ToString();
SqlConnection SqlConnection = new SqlConnection(connectionString);
SqlCommand SqlCommand = new SqlCommand();
try
{
SqlConnection.Open();
config
<connectionStrings>
<add name="NotMySqlServer" providerName="System.Data.SqlClient" connectionString="server=TEST\SQL2005;database=ADB;Integrated Security=True"/>
<add name="NotMy2SqlServer" providerName="System.Data.SqlClient" connectionString="server=TEST\SQL2005;database=ADB;Integrated Security=True"/>
</connectionStrings>
You can try :
if(ConfigurationManager.ConnectionStrings["MySqlServer"] == null) throw ...
If you're using .NET 4.5+ and have access to C# 6.0, you can make use of the null conditional operator (?) to try and get the connection string without automatically throwing an exception:
string connectionString = ConfigurationManager.ConnectionStrings["MySqlServer"]?.ConnectionString;
//------------------------------------------------------------------------HERE-^-HERE-------------
if (string.IsNullOrWhiteSpace(connectionString))
{
// Don't even bother trying to open the connection.
// Log the error and either rethrow the exception (throw;) or exit from your current context (return;).
//return;
//throw;
}
// If your code has made it this far, it means you have a valid connection string. Now try to use it.
using (var sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
using (var sqlCommand = new SqlCommand)
{
// Do stuff.
}
}
You can check if there are any connections strings by using count.
var count = ConfigurationManager.ConnectionStrings.Count;
if (count > 0)
{
//There is at least more then one connection string.
}
Update
public static class Extension
{
public static bool HasConnectionString(this ConnectionStringSettingsCollection value, string key)
{
try
{
return value[key].ConnectionString.Length > 0;
}catch
{
return false;
}
}
}
You can use the extension as follow.
if (ConfigurationManager.ConnectionStrings.HasConnectionString("MySqlServer"))
{
//If true you know there is a valid connectionstring.
}