ASP.Net web application connect to host SQL DataBase - c#

I have a simple Web API Application and I want to connect it to a DataBase presents in my host. This is in my web.config:
<connectionStrings>
<add name="JarasDB" connectionString="Data Source=localhost;Initial Catalog=JarasDB;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
And I'm going to test it with following codes:
public string Get(int id)
{
string connectionString = ConfigurationManager.ConnectionStrings["JarasDB"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
//
// Open the SqlConnection.
//
con.Open();
//
// The following code uses an SqlCommand based on the SqlConnection.
//
using (SqlCommand command = new SqlCommand("CREATE TABLE Customer(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date datetime);", con))
command.ExecuteNonQuery();
}
catch (Exception ex)
{}
}
return strings[id];
}
After publishing project in my host what happens is The Connection String will be add in ASP.NET Configuration page in Plesk panel:
After calling Get method I expect to create a table in my database but nothing happens. I want to know where is my problem.

The problem occurred because you're using SQL Server connection string to connect against MySQL database, which doesn't work as expected. Ensure that MySQL Connector .NET is referenced in your project (i.e. include MySql.Data.dll and all related assemblies), then replace your connection string from this one:
<!-- Wrong (SQL Server connection string) -->
<add name="JarasDB" connectionString="Data Source=localhost;Initial Catalog=JarasDB;Integrated Security=True;" providerName="System.Data.SqlClient" />
to this example:
<!-- Correct -->
<add name="JarasDB" connectionString="Server=localhost;Port=3306;Database=jarasdb;Uid=UserID;Pwd=XXXXX" providerName="MySql.Data.MySqlClient"/>
Additionally, it is necessary to use MySqlConnection and MySqlCommand from MySql.Data.MySqlClient namespace to execute DDL query:
// add this line on top of 'using' lines
using MySql.Data.MySqlClient;
public string Get(int id)
{
string connectionString = ConfigurationManager.ConnectionStrings["JarasDB"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(connectionString))
{
try
{
con.Open();
using (MySqlCommand command = new MySqlCommand("CREATE TABLE Customer(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date datetime);", con))
{
command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
// throw exception here
}
}
return strings[id];
}
Reference: MySQL Connector .NET Connection Strings

Related

C# - "Login failed for user 'Username'(SQL Server 2014)

I'm trying to connect to SQL Server 2014 using my C# code
<connectionStrings>
<add name="ConnectionString"
connectionString="Data Source=IP\\SQLNameSERVER,1433;Network Library=DBMSSOCN; Initial Catalog=MyDB; User ID=Username; Password=password;"/>
</connectionStrings>
string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection cn = new SqlConnection(ConnectionString))
{
query = "SELECT * FROM [MyTable]";
using (SqlCommand commandUserPortal = new SqlCommand(query, cn))
{
cn.Open();
}
}
but I get an error message:
Login failed for user 'Username'.
When I use the same credentials to connect to DB through SQL Server Management Studio, it works fine without any issues.
The user has db_datareader permission.
I also tried
<connectionStrings>
<add name="ConnectionString"
connectionString="Data Source=IP\\SQLNameSERVER,1433;Network Library=DBMSSOCN; Initial Catalog=MyDB; User ID=Username; Password=password;
providerName="System.Data.SqlClient"/>
</connectionStrings>
Use an accurate connection string via using Add connection from Visual studio.
How:-
Follow the next screen shots:-
1) View >> Server Explorer
2) Add Connection
3) Choose data source >> SQL Server
4) Type Server Name, SQL Server authentication , type username and password, and choose database.
5) Click Test Connection button.
6) The Connection that you created will be added here
7) Right click and choose properties
8) Finally copy and paste the connection string and use it , and replace the stars (********) with your password
Try to change setting in sql server for you database. Allow both sql and windows authentication. For steps with images, check here. I hope that you are not using windows authentication and also the DB server is reachable by your network. Everything else is looking ok to me.
Use the following as Connection String
<add name="DefaultConnection" connectionString="data source=192.168.0.1; initial catalog=DBNAME;persist security info=True;user id=UserId;password=Password;MultipleActiveResultSets=True ; Connect Timeout=10000" providerName="System.Data.SqlClient" />
Replace your Database name in the catalog,user id in user id and passeord in password
try to change your Connection String:
<add name="ConnectionString" connectionString="Data source=IP\SQLNameSERVER;Initial Catalog=DBname;User=Username;Password=Password; connection timeout=6000;" />
Also try to change your Code:
from:
using (SqlConnection cn = new SqlConnection(ConnectionString))
{
query = "SELECT * FROM [MyTable]";
using (SqlCommand commandUserPortal = new SqlCommand(query, cn))
{
cn.Open();
}
}
to:
using (SqlConnection cn = new SqlConnection(ConnectionString))
{
query = "SELECT * FROM [MyTable]";
cn.Open();
using (SqlCommand commandUserPortal = new SqlCommand(query, cn))
{
}
}

how to acess data using web service, getting error in connection string

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/

C# WinForms not accepting connection string user details

I have a connection string in App.config like so:
<add name="connectionString"
connectionString="Data Source=SERVER;Initial Catalog=DB;Integrated Security=True;User ID=domain\username;Password=12345;Connection Timeout=300"
providerName="System.Data.SqlClient" />
I then call the string in code behind like so:
string conSTR = System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
SqlDataReader reader;
using (SqlConnection sqlConn = new SqlConnection(conSTR))
using (SqlCommand cmd = new SqlCommand(SQLQuery, sqlConn))
{
sqlConn.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
.... stuff happens here
}
}
MY local account does not have access to the server but the service account passed into the connection string does.
The error I get is:
Cannot open database "DB" requested by the login. The login failed.
Login failed for user 'domain\MyUserName'.
For some reason it is completely ignoring the user name/password in the connection string and tries to connect using my account.
How can I fix that?
you have integrated security = true in your connection string, remove that.
That because you're specifying Integrated Security=True;. This overrules any other authentication settings, remove it and it will use the username and password supplied.

Keyword not supported in Connection String: 'database'

Very new to C# and VS2012.
I'm trying to connect to a local database connection.
Here is the code
string selectSql = "select * from Tasks";
string connectionString = "Data Source=adamssqlserver;database=master;Integrated Security=true;";
using (var cn = new SqlCeConnection(connectionString))
using (var cmd = new SqlCeCommand(selectSql, cn))
{
cn.Open();
using (var reader = cmd.ExecuteReader())
{
//do something
}
}
Here is the error
Keyword not supported: 'database'.
If I put in Initial Catalog first
"Data Source=adamssqlserver;Initial Catalog=etc;"
Then the error gives the same message but for "Initial Catalog".
Here is my data connection
You are using SqlCeConnection not a SqlConnection
This class (SqlCeConnection) is for Sql Compact Edition where the syntax rules of the connection string are different. For example:
Data Source=MyData.sdf;Persist Security Info=False;
Instead your connection string is for a Sql Server or Sql Server Express.
So, if your target database is a SqlServer db as your tag indicates then you need to use
using (var cn = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(selectSql, cn))
{
....
}
Instead of Data Source, try Server, e.g:
string connectionString = "Server=adamssqlserver;Database=master";
This website contains good information for setting up connection string. There are so many options I usually have to turn to a reference to get it set up correctly.
Just a reminder: when using MS Access databases, you need to use OleDbConnection and OleDbCommand, not SqlConnection and SqlCommand. 'Provider' in the connection string for SqlConnection is invalid AFAIK.
Are you missing the " from the connection string section.
Should be
<add name="StevenTestEntities"
connectionString="metadata=res://*/Model.TestModel.csdl|res://*/Model.TestModel.ssdl|res://*/Model.TestModel.msl;
provider=System.Data.SqlClient;
provider connection string="Data Source=Data Source=D000097;
Initial Catalog=StevenTest;
Integrated Security=True;MultipleActiveResultSets=True&qout;"
providerName="System.Data.EntityClient" />
Try that out.

Connect ASP.NET WebSite to SQL Database

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()
}

Categories

Resources