public static DataSet ParseDatabaseData(string sheetName)
{
string connectionString = "Provider=System.Data.SqlClient;Data Source= MHSPC56888_VM1\\SQLEXPRESS;Initial Catalog=xxxxxxx;User id=xx;Password=xxxxx;";
SqlConnection conn = new SqlConnection(connectionString);
string strSQL = "SELECT * FROM [" + sheetName + "$]";
SqlCommand cmd = new SqlCommand(strSQL, conn);
conn.Open();
DataSet dataset = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataset);
conn.Close();
return dataset;
}
The error show that 'provider' keyword is wrong.
Please help me to correct how to connect with Database through connection string?
You do not need to specify the Provider in the Connection String.
Try it like this:
public static DataSet ParseDatabaseData(string sheetName)
{
string connectionString = "Data Source= MHSPC56888_VM1\\SQLEXPRESS;Initial Catalog=xxxxxxx;User id=xx;Password=xxxxx;";
Instead of mentioning the connection string in the individual file itself, you can place the connection string in the web.config or app.config and use the config where ever required.
Sample for web.config place the connection string under the <configuration>, there you can provide the provider name:
<configuration>
<connectionStrings>
<add name="ConnString"
connectionString="Data Source= MHSPC56888_VM1\\SQLEXPRESS;Initial Catalog=xxxxxxx;User id=xx;Password=xxxxx;"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
and inside the file
public static DataSet ParseDatabaseData(string sheetName)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
Note: add using System.Configuration; for the ConfigurationManager.
Related
I have read several Stackoverflow suggestions and ways to store a connection string in web.config.
However I have an issue how to store my connection string and reference it.
My connection string looks like this
connString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"", fileName);
I can't quite add this to my connection string
<add name="ExcelConnection"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\""/>
Isn't quite working.
How do I secure my application by using the web.config to store connection strings?
Edit:
C# code that reads it
string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"", fileName);
DataSet data = new DataSet();
try
{
foreach (var sheetName in GetExcelSheetNames(connectionString))
{
using (OleDbConnection con = new OleDbConnection(connectionString))
{
var dataTable = new DataTable();
string query = string.Format("SELECT * FROM [{0}]", sheetName);
con.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(query, con);
adapter.Fill(dataTable);
data.Tables.Add(dataTable);
}
}
}
catch (Exception Ex)
{
}
Doesnt connect to database, its throw exception.
SqlConnection con = new SqlConnection("Data Source=.;InitialCatalog=CAFETERIADB; Integrated Security=True;");
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt;
DataSet ds = new DataSet();
private void CashForm_Load(object sender, EventArgs e)
{
con.Open();
da = new SqlDataAdapter("Select * FROM PhoneBook ORDER BY SLNo desc", con);
dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.Columns[0].Width = 10;
con.Close();
comboBox1.Items.Clear();
con.Open();
cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Name FROM PhoneBook order by SLNo asc";
cmd.ExecuteNonQuery();
dt = new DataTable();
SqlDataAdapter da1 = new SqlDataAdapter(cmd);
da1.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox1.Items.Add(dr["Name"].ToString());
}
con.Close();
here is my connection string:
<add name="CafeteriaDBConnectionString"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\CafeteriaDB.mdf;Integrated Security=True"
First of all, place your connection string in single location. As on connection string inside code and second in configuration file.
SqlConnection con = new SqlConnection("Data Source=.;InitialCatalog=CAFETERIADB; Integrated Security=True;");
To make it working first test your connection string.
Save notepad file as name.udl
double click and provide appropriate values if local server (pc name \SQLEXPRESS) or (.\SQLEXPRESS)
Click test and again open same udl file in notepad
copy the connection string it will be some thing like below but exclude provider part
Password=;Persist Security Info=True;User ID=;Initial Catalog=CafeteriaDB;Data Source=.\SQLEXPRESS
SqlConnection con = new SqlConnection("Password=***;Persist Security Info=True;User ID=***;Initial Catalog=CafeteriaDB;Data Source=.\SQLEXPRESS;")
I hope this will helps you.
I don't think in your code you are referring to the connection string you set up in config file. Instead, you hard-coded a new connection in the first line of your code.
If you are sure the connection string in config file works fine, you can put it into your code directly.
Change your first line code as:
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\CafeteriaDB.mdf;Integrated Security=True");
Or you can refer to connection string in config file.
string connectionString = DatabaseHelper.CafeteriaDBConnectionString;
SqlConnection con = new SqlConnection(connectionString);
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();
}
DataSet ds = new DataSet("Transactions");
using (SqlConnection conn = new SqlConnection("myConnectionString"))
{
SqlCommand sqlComm = new SqlCommand("[dbo].[GetFullTransactionList]", conn);
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
}
return ds;
Relevant content of app.config:
<configuration>
<connectionStrings>
<add name="myConnectionString"
connectionString="Data Source=LAPTOP-LT;Initial Catalog=myDb;User ID=sa;Password=abc"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
I'm getting this exception:
Format of the initialization string does not conform to specification
starting at index 0. Description: An unhandled exception occurred
during the execution of the current web request. Please review the
stack trace for more information about the error and where it
originated in the code.
Exception Details: System.ArgumentException: Format of the
initialization string does not conform to specification starting at
index 0.
Source Error:
Line 44: DataSet ds = new DataSet("Transactions");
Line 45: using (SqlConnection conn = new SqlConnection("myConnectionString"))
The correct way to refer a connection string in the app.config is:
string cnnString = ConfigurationManager.ConnectionStrings["yourCnnString"].ConnectionString;
using(SqlConnection conn = new SqlConnection(cnnString))
{
}
do not forget the final property ConnectionString
To use connection string from config file, you need to access it ConfigurationManager.
So it will be:
using (SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"]))
{
...
}
Refer to documentation to get more info
SqlConnection expect a real connection string not the key from app.config. Try to read it with
ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString
I want to backup my DB but I got a error:
ConnectionStrings cannot be used like a method
How can I resolve this?
string strCon = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True";
string sSQL = "BACKUP DATABASE Database TO DISK = 'D:\\Database.bak';";
using (SqlConnection connection = new SqlConnection(ConfigurationManager.Connectionstrings(strCon).ConnectionString))
{
SqlCommand command = new SqlCommand(sSQL, connection);
connection.Open();
command.ExecuteNonQuery();
}
You should directly use that variable as SqlConnection requires a string object containing a connection string and you are storing it in a string object itself.
So it would be simply like this:
using (SqlConnection connection = new SqlConnection(strCon))
{
SqlCommand command = new SqlCommand(sSQL, connection);
connection.Open();
command.ExecuteNonQuery();
}
Recommended: (to store it in Web.config)
<connectionStrings>
<add name="job" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" />
</connectionStrings>
Then access it like this: (using System.Configuration;)
ConfigurationManager.ConnectionStrings["job"].ConnectionString
ConnectionStrings is a collection. It must be used like:
ConfigurationManager.Connectionstrings[0].ConnectionString