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
Related
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);
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.
I've installed Oracle DB on another pc(A) and trying to establish the connection from my pc(B). Now when I'm trying to debug the application I get this error- "[DBNETLIB][ConnectionOpen (ParseConnectParams()).]Invalid connection."
public void InsertionTest()
{
string cmdText = #"Insert into O_TEST_TABLE (ID,Name,MOBILE) Values (4, 'rD','798984');";
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["HR"].ConnectionString;
using (OleDbConnection con = new OleDbConnection(ConnectionString))// "Provider=SQLOLEDB; DATA SOURCE=172.16.1.220:1521/orcl;PASSWORD=hr;PERSIST SECURITY INFO=True;USER ID=hr"))
using (OleDbCommand cmd = new OleDbCommand(cmdText, con))
{
con.Open();
int rowsUpdated = cmd.ExecuteNonQuery();
if (rowsUpdated == 0)
{
Console.WriteLine("Failed!!!");
}
else
{
Console.WriteLine("Success.");
}
}
}
In my web config file, the connection string is-
<connectionStrings>
<add name="HR" connectionString="Provider=SQLOLEDB;Initial Catalog=HR;DATA SOURCE=172.16.1.13:1521/orcl;PASSWORD=hr;PERSIST SECURITY INFO=True;USER ID=hr; OLEDB.NET=True " />
</connectionStrings>
I feel provider should be Provider=OraOLEDB.Oracle
I'm new to Asp.Net and now I'm facing this problem. I've tried many way as possible I get from google and here. But I still cannot find a solution for this. I've tried to change the Data Source to 127.0.0.1, but I still get the same error. It actually works to connect to database when I'm using MySql.Data.MySqlClient. But fail when I'm using System.Data.SqlClient
Can you all help me? Thank you very much.
Code Behind:
private DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["WebAppConnStringSql"].ConnectionString;
using (SqlConnection cons = new SqlConnection(constr))
{
using (SqlCommand cmds = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmds.CommandType = CommandType.Text;
cmds.Connection = cons;
sda.SelectCommand = cmds;
**sda.Fill(dt);** //Error occurs here
}
}
return dt;
}
Web.config
<connectionStrings>
<add name="WebAppConnStringSql"
connectionString="Data Source=localhost;Initial Catalog=vbsite;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
The Error:
*An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)*
SqlException was unhandled by user code
You should open connection SqlConnection.Open():
using (SqlConnection cons = new SqlConnection(constr))
{
cons.Open();
using (SqlCommand cmds = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmds.CommandType = CommandType.Text;
cmds.Connection = cons;
sda.SelectCommand = cmds;
**sda.Fill(dt);** //Error occurs here
}
}
return dt;
}
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