i trying to run query using C#, i am getting the following problem
An OLE DB Provider was not specified in the ConnectionString. An example would be, 'Provider=SQLOLEDB;
my code
string strConString = System.Configuration.ConfigurationManager.ConnectionStrings["WorkflowConnStr"].ConnectionString.ToString();
string sqlstr = "select * from table"
OleDbConnection myConnection = new OleDbConnection(strConString);
try
{myConnection.Open();}
catch (Exception err)
{ System.Diagnostics.Debug.WriteLine(err.Message); }
OleDbCommand myCommand = new OleDbCommand(sqlstr, myConnection);
OleDbDataReader reader = myCommand.ExecuteReader();
web.config
<add name="WorkflowConnStr" connectionString="Data Source=Server;Initial Catalog=DBName;user id=usr;password=password" providerName="System.Data.OleDb.OleDbConnection"/>
any suggestion ?
Try adding this to your connection string,
Provider=SQLNCLI10.1
So it would be;
<add name="WorkflowConnStr" connectionString="Data Source=Server;Initial Catalog=DBName;user id=usr;password=password;Provider=SQLNCLI10.1" providerName="System.Data.OleDb.OleDbConnection"/>
Use SqlConnection instead of OleDbConnection.
Related
I'm trying to connect to a database, but it seems like my connection is not going through. I am using C# MVC for the webpage I'm creating. How can I fix the following error:
System.ArgumentException: 'Keyword not supported: 'metadata'.'.
The error is occuring on the line using (Sqlconnection con = new Sqlconnection(conStr)). What am I doing wrong on this line and is this how you call your SQL query in C# MVC?
string conStr = ConfigurationManager.ConnectionStrings["Training_DatabaseEntities"].ConnectionString;
List<FisYear> YerFis = new List<FisYear>();
using (SqlConnection con = new SqlConnection(conStr))
{
SqlCommand cmd = new SqlCommand("select * from [dbo].[FiscalYear]", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
FisYear fy = new FisYear();
fy.FisDate = rdr["ST_FI"].ToString();
YerFis.Add(fy);
}
SelectList list = new SelectList(YerFis, "ST_FI", "FisDate");
ViewBag.DropdownList = list;
}
You're almost certainly trying to use an entity framework connection string to open a connection via new SqlConnection, which won't work.
If you look in your web.config file you'll probably see something similar to:
<connectionStrings>
<add name="Training_DatabaseEntities" connectionString="metadata=res://*/Entity.csdl|res://*.............provider=System.Data.SqlClient;provider connection string=............." />
</connectionStrings>
You could try parsing the connection string by hand to retrieve the bit you actually want, a brief web search suggests that the EntityConnectionStringBuilder may be of use to retrieve it programmatically, here's an example of doing that in a console app:
var connectionString = ConfigurationManager.ConnectionStrings["Training_DatabaseEntities"]
.ConnectionString;
var entityConnectionStringBuilder = new EntityConnectionStringBuilder(connectionString);
var sqlConnectionConnectionString = entityConnectionStringBuilder.ProviderConnectionString;
Console.WriteLine($"EF Connection String: {connectionString}");
Console.WriteLine($"SqlConnection Connection String: {sqlConnectionConnectionString}");
This gives the output (my emphasis):
EF Connection String: metadata=res:///Models.Model1.csdl|res:///Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=cntrra02-sql-rs;initial catalog=Training_Database;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"
SqlConnection Connection String: data source=cntrra02-sql-rs;initial catalog=Training_Database;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework
Which shows a connection string that can be passed into a SqlConnection instance.
I am trying to create page in asp.net page and I am getting the following error
Error:-System.NullReferenceException: Object reference not set to an instance of an object. at TestdateAssistor.user_info.Button1_Click1(Object sender, EventArgs e)
at this line
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=LAPTOP-O9SI19I0\SQLEXPRESS;Integrated Security=True"].ConnectionString);
This is my complete code
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"].ConnectionString);
conn.Open();
String insert = "insert into Table (NAME,ADDRESS,MOBILE NO,ADHAR NO,DOB) values (#name,#add,#mob,#adhar,#dob)";
SqlCommand com = new SqlCommand(insert,conn);
com.Parameters.AddWithValue("#name",TextBox1.Text);
com.Parameters.AddWithValue("#add",TextBox2.Text);
com.Parameters.AddWithValue("#mob",TextBox3.Text);
com.Parameters.AddWithValue("#adhar", TextBox4.Text);
com.Parameters.AddWithValue("#dob", TextBox5.Text);
com.ExecuteNonQuery();
Response.Write("Successful Registration!!");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error:-" + ex.ToString());
}
What changes should I make in the connection string?
You’re using the connection string as a key to your connection strings defined in the Web.config. So you need to define the connection string there and give it a name, then reference it in the code by name:
Web.config:
<connectionStrings>
<add name="myConnectionString" connectionString="Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True" />
</connectionStrings>
Code:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
The ConnectionStrings is a collection automatically built for you by the framework. Its content is retrieved from the web.config where you should have it defined in the proper section.
Then you retrieve its value passing the Name between the square brackets not the whole connectionstring.
string cnString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
SqlConnection conn = new SqlConnection(cnString);
and in your web.config you add the proper definition for your connectionstring
<configuration>
<connectionStrings>
<add name="MyConnection" connectionString="Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"/>
</connectionStrings>
.....
</configuration>
Error:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"].ConnectionString);
Solution 1:
in main program (.cs)
SqlConnection conn = new SqlConnection("Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True");
Solution 2:
in web.config
<configuration>
<connectionStrings>
<add name="MyConnection" connectionString="Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"/>
</connectionStrings>
</configuration>
in main program (.cs)
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;);
reference: https://msdn.microsoft.com/en-us/library/d7469at0(v=vs.110).aspx
I am working with asp.net web services using c# need to access the database in web service but getting error in connection string can any one tell me how to specify the connections string of database here..
here is my code here I am using connection string as i use the string in web form..I am beginner so please guide me in step by step manner or reffer any clear and easily understandable manner as I could not get the point how connection sting is being specified in no of tutorials..
[WebMethod(Description = "show student data")]
public DataSet values(int a)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database.mdf;Integrated Security=True;User Instance=True"].ConnectionString);
SqlCommand cmd = new SqlCommand("Select * from STUDENT where stdID='"+a+"'", con);
SqlDataReader r;
r = cmd.ExecuteReader();
r.Read();
foreach
return r;
SqlDataAdapter ada = new SqlDataAdapter("Select * from STUDENT where stdID='" + a + "'", con);
DataSet ds = new DataSet();
ada.Fill(ds);
return ds;
}
Here your just to provide name of connection string in .ConnectionStrings[""] bracket and put your connection string in web.config file as per below.
<connectionStrings>
<add name="Dbconnection"
connectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database.mdf;Integrated Security=True;User Instance=True" ;
providerName="System.Data.SqlClient" />
</connectionStrings>
add this connection string in configuration manager tag in web.config file and write following connection
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Dbconnection"].ConnectionString);
add in comment if you need any more help.
Your connection string is a bit wrong... try something like
SqlConnection con = new SqlConnection(
"Data Source=.\\SQLEXPRESS;Initial Catalog=PUTYOURDATABASENAMEHERENOTTHEFILENAME;Integrated Security=True;User ID=YourUserID;Password=YourPassword");
"The User Instance feature is deprecated with SQL Server 2012, use the SQL Server Express LocalDB feature instead." https://www.connectionstrings.com/sql-server/
I tried to play with Database creation and queries. In order to do that I started a C# form application, added a Database Service then added a Table with some values, then I wanted to use some code to retrieve those values.
Here's the code:
string conn = "data source = ./SQLEXPRESS; AttachDbFilename=C:\\Users\\Asus\\Desktop\\RobaMia\\SQLSERVER\\WindowsFormsApplication3\\WindowsFormsApplication3\\Database1.mdf; Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlConnection sql = new SqlConnection(conn);
sql.Open();
MessageBox.Show("Connection Opened");
sql.Close();
Sadly the program throws an exception when comes to the open because it seems it cannot find the Database...
"Server not found or not accessible"
I don't know what is the problem, what would you suggest?
Ok, it seems to work now but I get an incorrect syntax for my query
string conn = "Server=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Asus\Desktop\RobaMia\SQLSERVER\WindowsFormsApplication3\WindowsFormsApplication3\Database1.mdf; Integrated Security=True;Connect Timeout=30;User Instance=False";
string queryString = "SELECT * FROM Table";
SqlConnection sql = new SqlConnection(conn);
sql.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand(queryString, sql);
/* --->here I get the error*/ command.ExecuteNonQuery();
DataSet data = new DataSet();
adapter.Fill(data);
MessageBox.Show(data.ToString());
sql.Close();
It looks like the data source part your connection string is wrong. It should be:
"Data source=.\\SQLEXpress"
Complete:
string conn = "Data source=.\\SQLEXpress; AttachDbFilename=C:\\Users\\Asus\\Desktop\\RobaMia\\SQLSERVER\\WindowsFormsApplication3\\WindowsFormsApplication3\\Database1.mdf; Integrated Security=True;Connect Timeout=30;User Instance=True";
https://www.connectionstrings.com/sql-server/
As an additional note, you may be best off placing this in an app.config or web.config file just encase you reference the connection string multiple times and later you decide to change the value of it.
Have you tried(LocalDB), instead of SQLExpress?
"Server=(localdb)\\Test;Integrated Security=true;AttachDbFileName= myDbFile;"
http://www.asp.net/mvc/overview/getting-started/introduction/creating-a-connection-string
I am currently trying to establish a connection between an ASP.NET web site project and a Database built by SQL Server 2008 R2.
The way I am required to do so is to use the connectionString from the Web.config page, but I have no idea what value to give it or how to establish a connection using said value. (Using C#)
Any help would be appreciated, as I found next to no information about the subject.
Here is the (default) value that is currently in the Web.config page:
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
Use Configuration Manager:
using System.Data.SqlClient;
using System.Configuration;
string connectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
using(SqlConnection SqlConnection = new SqlConnection(connectionString));
//The rest is here to show you how this connection would be used. But the code above this comment is all you really asked for, which is how to connect.
{
SqlDataAdapter SqlDataAdapter = new SqlDataAdapter();
SqlCommand SqlCommand = new SqlCommand();
SqlConnection.Open();
SqlCommand.CommandText = "select * from table";
SqlCommand.Connection = SqlConnection;
SqlDataReader dr = SqlCommand.ExecuteReader(CommandBehavior.CloseConnection);
}
This article about Connect to SQL Server Using SQL Authentication in ASP.NET will probably give you a better idea of what need to be done.
As a pre check, just check if your mssqlserver services are running.
string connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = commandText;
// command.Parameters.AddWithValue("#param", value);
connection.Open();
command.ExecuteNonQuery(); // or command.ExecuteScalar() or command.ExecuteRader()
}