One connection for whole of the form - c#

hi guys I have this connection and I have to type it every time when I need my db is there any way to type it once and using it in every button by con.open(); and con.close();
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\db\\it.accdb");

Yes. Use a function.
private OleDbConnection GetConnection()
{
return new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\db\\it.accdb");
}
Then when you need a connection, call it:
var con = GetConnection();
Functions promote code re-use. This code can further be improved by moving the connection string into a configuration file.

Related

Exception on Open in OleDbConnection

When I am trying to open a excel into one of my windows service using following code it is throwing "Value cannot be null. Parameter name: source" on objConn.Open(); Can any one please help me.
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
LogManager LogWrite = new LogManager();
try
{
string conn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Repository\RuleExcel\Rules_Repository_2018-06-28_03-41-29-133.xlsx;Extended Properties='Excel 12.0;HDR=YES;';";
LogWrite.WriteLog(conn);
// Create connection object by using the preceding connection string.
objConn = new OleDbConnection(conn);
LogWrite.WriteLog(objConn.DataSource);
// Open connection with the database.
objConn.Open();
try this below code, it works for me :
using (OleDbConnection objConn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + #";Extended Properties=""Excel 12.0;IMEX=1;HDR=YES;"""))
{
objConn.Open();
}

Access database in C# console application

The current problem I'm having is an error message that it could not find file C: now I dont know what the problem is because the file is in that location. I have I tried in both .accbd and .mbd.
private static OleDbConnection GetConnection()
{
OleDbConnection conn = new OleDbConnection();
String connectionString =
#"Provider=Microsoft.JET.OlEDB.4.0;"
+ #"Data Source= C:\Temp\F1\Docs\Expeditors Project\Table1.accbd";
conn = new OleDbConnection(connectionString);
conn.Open();
return conn;
}
Do you tried another Provider?
For example:
Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Temp\F1\Docs\Expeditors Project\Table1.accbd;
try \\ in Data Source Path
like below -
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\Data\test.mdb;Persist Security Info=False");
try this `
`private static OleDbConnection GetConnection() throws SQLException{
{
if (conn==null)
{
try{ OleDbConnection conn = new OleDbConnection();
String connectionString = #"Provider=Microsoft.JET.OlEDB.4.0;"
+ #"Data Source= C:\Temp\F1\Docs\Expeditors Project\Table1.accbd";
conn = new OleDbConnection(connectionString);
conn.Open();
return conn;
}}
catch(Exception e){
e.printStackTrace();
}

ServerConnection doesn't work with a connection string

I use below code to create backup from my database in c#.net. but when I run Code I getting this error :
Failed to connect to server Data Source=.;Initial Catalog=AngularJs;Integrated Security=True.
my code to do this is :
ServerConnection con = new ServerConnection("Data Source=" + txtServerName.Text + ";Initial Catalog=" + drpDatabases.SelectedItem.ToString() + ";Integrated Security=True");
Server server = new Server(con);
Backup source = new Backup();
source.Action = BackupActionType.Database;
source.Database = drpDatabases.SelectedItem.ToString();
BackupDeviceItem destination = new BackupDeviceItem(Path, DeviceType.File);
source.Devices.Add(destination);
source.SqlBackup(server);
con.Disconnect();
Where is Problem ? Why this is not work ?
I tested connections string with sqlconnection its work fine and open very well .
Try this:
ServerConnection con= new ServerConnection(new SqlConnectionStringBuilder(cnstring).DataSource);
Your code is wrong, use:
ServerConnection con = new ServerConnection(
new SqlConnection(
"Data Source=" + txtServerName.Text + ";Initial Catalog="
+ drpDatabases.SelectedItem.ToString()
+ ";Integrated Security=True"));
The ServerConnection(string) overload expects an instance name, not a connection string. You can simply write new ServerConnection(".") or :
var con = new ServerConnection(txtServerName.Text);
The error message tells you that ServerConnection tried to connect to a server having a name the same as the entire connection string and failed.
A ServerConnection represents a connection to a specific server, not a database, so it doesn't need a SqlConnection object. If you supply one, it's used only to extract the relevant information.
Try This:
SqlConnection con = new SqlConnection("Data Source=" + txtServerName.Text + ";Initial Catalog=" + drpDatabases.SelectedItem.ToString() + ";Integrated Security=True");
SeverConnection scon = new ServerConnection(con);
Server svr = new Server(scon);
because I think you're passing an incorrect parameter for the ServerConnection.

Write Data to Excel using Oledb

Is it possible to write data using Oledb into a common excel ?
There are no table structure or anything, it's a user document.
When I tried, i had always an OleDbException
"INSERT" query reply :
Operation must use an application that can be updated.
"UPDATE" query reply :
No value given for one or more required parameters.
My code:
using (OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + #"C:\Users\[...]\Classeur.xls" + ";Extended Properties=\"Excel 8.0;HDR=NO;IMEX=1;READONLY=FALSE\""))
{
connection.Open();
OleDbCommand commande = new OleDbCommand(
"INSERT INTO [Feuil1$](F1,F2,F3) VALUES ('A3','B3','C3');", connection);
commande.ExecuteNonQuery();
connection.Close();
connection.Dispose();
}
New test (without sucess !) :
using (OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + #"C:\Users\[...]\Classeur.xls" + ";Extended Properties=\"Excel 8.0;HDR=NO;IMEX=1;READONLY=FALSE\""))
{
string column = "A";
string row = "1";
string worksheetName = "Feuil1";
string data = "TEST";
connection.Open();
string commandString = String.Format("UPDATE [{0}${1}{2}:{1}{2}] SET F1='{3}'", worksheetName, column, row, data);
OleDbCommand commande = new OleDbCommand(
commandString, connection);
connection.Close();
connection.Dispose();
}
I finally found !
Simple question of IMEX ( So many hours lost for that !)
So if anyone have the same issue :
//for reading data
Extended Properties=\"Excel 8.0;HDR=NO;IMEX=1;READONLY=FALSE\"
//for writing data
Extended Properties=\"Excel 8.0;HDR=NO;IMEX=3;READONLY=FALSE\"
This IMEX situation for Writing Data was driving me crazy for months, I had to remove it to make it work.
I just found [CheapD] answer and it works flawless, Thank you Cheap.
I would suggest to add the MODE parameter:
Extended Properties='Excel 12.0; HDR=Yes; IMEX=3; MODE=Share; READONLY=False';

update excel cells with its uppercase text

i have the following problem with an excel file that i want to uppercase the values of its respective cells in C# with the next code:
DbProviderFactory factory =
DbProviderFactories.GetFactory("System.Data.OleDb");
DbConnection connection = factory.CreateConnection();
string stringConnection = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=NO;IMEX=1'",
excelPath);
connection.ConnectionString = stringConnection;
connection.Open();
DbCommand updateExcel =
factory.CreateCommand();
updateExcel.CommandText =
"UPDATE [sheet1$] SET lastname = UCASE(lastname), name = ucase(name)";
updateExcel.Connection = connection;
updateExcel.ExecuteNonQuery();
conection.Close();
connection.Dispose();
and it raise an oledbexception about parameters doesnt specified, anybody could help me?
If you are trying to connect to an Excel 2007 or 2010 spreadsheet you will need the following connection string...
OleDbConnection xlconnection = new OleDbConnection();
xlconnection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + #";Extended Properties='Excel 12.0;HDR=YES;IMEX=1'"

Categories