This is my code
string connectionString = #"Provider=SQLOLEDB;Data Source=Machine Name;Initial Catalog=MyTestDatabase;";
OleDbConnection conn = new OleDbConnection(connectionString);
DataTable result = new DataTable();
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand("get_holidays", conn);
cmd.CommandType = CommandType.StoredProcedure;
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(result);
}
$exception {"Invalid authorization specification"} is thrown during
conn.open().
Connection string format:
Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;
or
Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;
Add Integrated Security=SSPI to your connection string especially when username and password are not specified. In this case current Windows account credentials are used for authentication.
Provider=SQLOLEDB;Data Source=ServerName;Integrated Security=SSPI;Initial Catalog=databaseName
Try this connection string
Provider=SQLOLEDB;Data Source=Machine Name;Initial Catalog=MyTestDatabase;Integrated Security=SSPI
If will not work locally - then you have no access to your Sql Server
no username and password in connection string
Related
I am trying to connect to the SQL server with the below connection string but it is giving this "error Connect Timeout expired"
I have tried to telnet and it connected successfully. However, from the code, I cannot connect even though I have tried to specify the default port.
Is there anything am doing wrong? Thank you in advance.
string _connectionString = #"Server=myIP,1433;Database=myDB;User Id=myID;Password=myPass;";
using (MySqlConnection con = new MySqlConnection(_connectionString))
{
con.Open();
string sqlQuery = "SELECT * FROM Inventory";
using (MySqlCommand cmd = new MySqlCommand(sqlQuery, con))
{
MySqlDataReader result = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (result.Read())
{
}
con.Close();
}
}
Telnet result
Use backslash if you have an instance of your SQL Server "Server=myIP\sqlexpress".
If the server is your local machine, use Windows Authentication instead:
"Server= localhost; Database= myDB; Integrated Security=True;"
Or you can use App.Config to configure your SQL connection`, this is how I configure mine using Windows Authentication, not username and password. First, add an App.config to your application. Then add this:
<connectionStrings>
<add name="SqlConnectionString" connectionString="Data Source=localhost;Initial Catalog=myDB;Integrated Security=true"/>
</connectionStrings>
And on your program:
string _connectionString = string connString = ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString;
using (con = new SqlConnection(_connectionString))
{
string sqlQuery = "SELECT * FROM Inventory";
SqlCommand cmd = new SqlCommand(sqlQuery, con)
con.Open();
SqlDataReader result = cmd.ExecuteReader();
while (result.Read())
{
}
con.Close();
}
Don't forget to add using directive:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
My database layout looks like this:
-App_Data
-Database.mdf
-Database_log.ldf
and this is my code:
string strConn = "Data Source=.\\SQLEXPRESS;Initial Catalog=Database;Integrated Security=True;";
SqlConnection myConn = new SqlConnection(strConn);
myConn.Open();
String strSQL = "INSERT INTO dbo.member (Id, Password, Name, Jobtitle,level,phone) VALUES ('a01', '123', 'bobo', 'Tester','1','010919')";
SqlCommand myCommand = new SqlCommand(strSQL, myConn);
myConn.Close();
When I test in browser, however, it sends an error message and stops in this code "myConn.Open();"can't find server
Why is this happening?
change
string strConn = "Data Source=.\\SQLEXPRESS;Initial Catalog=Database;Integrated Security=True;";
to
string strConn = #"Data Source=.\SQLExpress;Initial Catalog=Database;Integrated Security=True";
Attach a database file, located in the data directory, on connect to a
local SQL Server Express instance
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|dbfilename.mdf;Database=dbname;
Trusted_Connection=Yes;
so your connection string should be similar to below, replace database name corectly
string strConn =#"Server=.\SQLExpress;AttachDbFilename=|DataDirectory|Database.mdf;Database=dbname; Trusted_Connection=Yes;";
using (SqlConnection myConn = new SqlConnection(strConn))
{
string strSQL = "INSERT INTO dbo.member (Id, Password, Name, Jobtitle,level,phone) VALUES ('a01', '123', 'bobo', 'Tester','1','010919')";
myConn.Open();
using(SqlCommand myCommand = new SqlCommand(strSQL, myConn))
{
myCommand.ExecuteNonQuery(); // you haven't execute the insert
}
}
I am trying to fetch the Server Name using C# for that I am trying blow mentioned code.
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
con = new SqlConnection("Data Source=.;Database=Master;Integrated Security=SSPI");
con.Open();
cmd = new SqlCommand("select * from sysservers where srvproduct='SQL Server'", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
ServerCollection.Add(dr[2].ToString());
}
dr.Close();
it's give me Exception like Login faild for user Dhaval.patel so can anyone please help how to connect using window's Authetication in C#.
Try to Put Integrated Security = true like this
con = new SqlConnection("Data Source=.;Database=Master; Integrated Security=true");
It should be like :-
("Server= localhost; Database=Master;Integrated Security=SSPI, Integrated Security=True");
If you have a named instance of SQL Server, you'll need to add that as well,
e.g.,
"Server=localhost\sqlexpress"
Here I created a barchart using a Windows application with C#. I retrieve the data from stored procedure and bind the with barchart. So far I wrote this code:
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=ARUN-PC/SQLEXPRESS;Initial Catalog=InsightPro_Latest ;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SumofPowders";
DataSet ds = new DataSet();
da.Fill(ds);
InsightPro_BarChart.DataSource = ds;
InsightPro_BarChart.DataBind();
con.Close();
}
catch
{
}
Now I faced the error: The ConnectionString property has not been initialized. I don't know where I did the mistake.
Can anyone please clarify my doubt in coding also? Thanks in advance.
Provide connection string to SqlConnection (otherwise it will not know which database connect to):
string connectionString = "Server=Name;Database=DbName;User=Foo;Password=Bar";
SqlConnection con = new SqlConnection(connectionString);
// you can also set connection string via property
// con.ConnectionString = connectionString;
Usually connection strings are stored in configuration file of your application in <connectionStrings> section (see Connection Strings and Configuration Files):
<connectionStrings>
<add name="myConnection"
connectionString="Server=Name;Database=DbName;User=Foo;Password=Bar"
providerName="System.Data.SqlClient"/>
</connectionStrings>
You can use ConfigurationManager to get connection string from config file (you should add reference to System.Configuration assembly):
string connectionString =
ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString;
You need add the connection string to you SQL.
For example:
string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;";
Then do the needed SqlConnection as:
SqlConnection con = new SqlConnection(connectionString);
More on Connection strings: http://www.connectionstrings.com/sql-server-2005/
You can add your database connection details in the config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Test" connectionString="Data Source=.;Initial Catalog=OmidPayamak;IntegratedSecurity=True" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Once you have the configuration, you then need to access the same for your connection.
You can use ConfigurationManager:
using System;
using System.Configuration;
var connectionString = ConfigurationManager.ConnectionStrings["Test"];
Then use the SqlConnection to pass the connection and start off:
SqlConnection con = new SqlConnection(connectionString);
Try this
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword";
conn.Open();
Web.config
<connectionStrings>
<add name="ApplicationServices" connectionString="copy connection string here"
/>
</connectionStrings>
SqlCommand command = new SqlCommand();
command.CommandText = "SumofPowders";
command.CommandType = CommandType.StoredProcedure;
con.open();
SqlDataAdapter da = new SqlDataAdapter(command,con);
DataSet ds = new DataSet();
da.Fill(ds);
InsightPro_BarChart.DataSource = ds;
InsightPro_BarChart.DataBind();
add a connection string to your webconfig inside ConnectionString tag
<add name="constr" connectionString="Data Source=ARUN-PC/SQLEXPRESS;Initial Catalog=InsightPro_Latest ;User ID= YourServersername ;Password=YourServerPassword" providerName="System.Data.SqlClient"/>
in your code behind
string conn = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection con = new SqlConnection(conn);
I'm trying to bind my sql table with the grid view using the following code:
string connectionString = WebConfigurationManager.ConnectionStrings["Gen_Lic"].ConnectionString; //<-- error
string selectSQL = "SELECT * FROM Gen_Lic";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "Gen_Lic");
Gen_Lic_Grid.DataSource = ds;
Gen_Lic_Grid.DataBind();
But I don't know where I'm going wrong with this, but I'm getting an error:
Object reference not set to an instance of an object.
Any suggestions?
This is my web.config file:
<connectionStrings>
<add name="Gen_LicConnectionString" connectionString="Data Source=ESHA\SQLEXPRESS;Initial Catalog=Gen_Lic;User ID=sa;Password=sa#" providerName="System.Data.SqlClient" />
</connectionStrings>
Use this link to add connection string in web config.
http://www.aspdotnet-suresh.com/2011/11/write-connection-strings-in-webconfig.html
you were using a different name in the call and webconfig.
string connectionString = ConfigurationManager.ConnectionStrings["Gen_LicConnectionString"].ConnectionString;
You didn't open SqlConnection. you have to Open Connection before creating a command variable.
string connectionString = WebConfigurationManager.ConnectionStrings["Gen_Lic"].ConnectionString; //<-- error
string selectSQL = "SELECT * FROM Gen_Lic";
SqlConnection con = new SqlConnection(connectionString);
con.Open();// Need to Open Connection before to Create SQL Comamnd
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "Gen_Lic");
Gen_Lic_Grid.DataSource = ds;
Gen_Lic_Grid.DataBind();
Always check your connection string and set the connection to open.
to make it safe, set always your connection to close.
if(connection.State == ConnectionState.Open)
connection.Close();
connection.Open();