I am having problems connecting to a SQL Server database from C#.
The exception that returns is the login has failed for the specified user, which is clear enough. However, I am not sure why it fails as the username and password are definitely correct. Are there any settings I need to enable on the SQL Server to allow this to happen, as it is a default express install,
Thanks,
Below is my connection code if I'm missing anything obvious.
static void Main(string[] args) {
try
{
SqlConnection con = new SqlConnection(#"Data Source = .\SQLEXPRESS;Initial Catalog=furniture_display;User ID=login;Password=login");
con.Open();
Console.WriteLine("all ok");
con.Close();
}
catch (SqlException err)
{
Console.WriteLine(err);
}
}
According to your code Data Source = .\SQLEXPRESS, you'r trying to connect to a local server. If so you don't need any ID and Password. And be aware of using Catalog, it's somehow tricky and I hate it. To know how it's working, check this out.
Actually I'm using this code and it works like a charm:
SqlConnection con = new SqlConnection(#"Server = localhost; Database = furniture_display; Integrated Security=True;");
Related
Just learning how to create an Windows Forms application via Tom Owsiak C# Windows Forms video tutorials and I'm stuck at the database project (contacts management system) which requires to store data to a database.
I've been following his every single step yet somehow manage to mess up the application writing process. The error happen at the line
SqlConnection conn = new SqlConnection(connString);
Have been searching stackExchange for a while now and try possible solution but still couldn't work it out.
// error occurs here, stated key word not supported, connection timeout
using (SqlConnection connectforfucksake = new SqlConnection(connString))
{
try
{
connectforfucksake.Open(); // open the connection
// create the new SqlCommand object
command = new SqlCommand(insert, connectforfucksake);
command.Parameters.AddWithValue(#"Data_Added", dateTimePicker1.Value.Date);
command.Parameters.AddWithValue(#"Company", txtCompany.Text);
command.Parameters.AddWithValue(#"Website", txtWebsite.Text);
command.Parameters.AddWithValue(#"Title", txtTitle.Text);
command.Parameters.AddWithValue(#"First_Name", txtFName.Text);
command.Parameters.AddWithValue(#"Last_Name", txtLName.Text);
command.Parameters.AddWithValue(#"Address", txtAddress.Text);
command.Parameters.AddWithValue(#"City", txtCity.Text);
command.Parameters.AddWithValue(#"State", txtState.Text);
command.Parameters.AddWithValue(#"Postal_Code", txtPostalCode.Text);
command.Parameters.AddWithValue(#"Mobile", txtMobile.Text);
command.Parameters.AddWithValue(#"Note", txtNote.Text);
command.ExecuteNonQuery(); // pushing whatever in the form into table
}
catch (Exception ex)
{
MessageBox.Show(ex.Message); // show the unforeseen error
}
}
Expected application to take result and then store them into database but it seem like the SqlConnection object instantiate is causing the error.
It sounds like your connection string is simply wrong; most likely, you meant "Connect Timeout" rather than "connection timeout". A basic connection string that includes a connect timeout might be something like:
Data Source=.;Initial Catalog=master;Integrated Security=True;Connect Timeout=42
I have looked for multiple Solutions for my Problem.
I have a program, that needs to insert/update/select data from a Database nearly all the time. And the program itself works, but the problem is, it should also work in a production system with our staff and this needs to be secure.
One of the main thing is:
How do I manage, that the program can connect to the DataBase from our Staff PC's, without mentioning in the Connection String the Username and Password.
Some People said, I should use Windows Authentication.
But where do I mention the user/password that will be used to connect to the database? I need it to work in a way, people cant see the Login-Data to manipulate the DB-Server, but the programm itself should still be able to connect to it.
How can I do it?
Here are 2 connection strings my Visual Studio generated for me:
"Data Source=domain,Port;Initial Catalog=Zeiterfassung;Persist Security Info=True;User ID=sa;Password=PW"
"Data Source=domain;Initial Catalog=Zeiterfassung;Integrated Security=True"
First one works fine, but the password is visible there. That shouldn't be. Even if I store it somewhere in the program, a decompiler will still make it visible.
Will the second string really work on ANY PC out there, that has internet connection and the program? So no one can see the Information need to Manipulate the program outside of the program or the Admin itself? Right now I can test on authorized PC's, that have a user which is manually added as authorized on the DB-Server, but what is with other users? The should only be able to connect to the DB with the Program, not manually with their Windows Account in MSSMS. Last thing should really be forbidden.
A Simple Code Snippet to clarify how the Connection looks for Example:
class Utility {
private static SqlConnection con;
static Utility() {
con = new SqlConnection();
con.ConnectionString = Properties.Settings.Default.DBPath1;
}
public static DataTableReader getSelectDataTableReader(string selectCommand, SqlParameter[] parameter) {
SqlDataAdapter adapter = new SqlDataAdapter(selectCommand, con);
if (parameter.Length > 0) {
adapter.SelectCommand.Parameters.AddRange(parameter);
}
DataSet ds = new DataSet();
try {
adapter.Fill(ds, "Table");
} catch (Exception ex) {
writeToLog(ex.Message);
return null;
}
return ds.Tables["Table"].CreateDataReader();
}
Below is a concise version of my code as it pertains to db access.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
namespace DataAccess
{
public class DbConnection
{
public string connString = "Data Source=[Insert IP];Initial Catalog=MOSAIQ;Persist Security Info=True;User ID=[Insert User];Password=[Insert Password]";
public void CreateConnection()
{
using (SqlConnection conn = new SqlConnection(connString))
{
try
{
conn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
For security reason I've removed IP and user credentials. That being said I copied the above connection string directly from the properties of the server explorer which successfully connected to my db.
While stepping through this code the following error is caught upon executing conn.Open()
Seems pretty obvious that there is an issue during validation. The credentials supplied are those used for SQL authentication.
Why is it that I can connect via server explorer but not directly via my code? What does Visual Studio's do for me that I can't seemingly do myself?
Ports are open, firewall is not an issue. I'm stumped and as a rookie in this matter would appreciate further guidance.
I'm trying to connect to SQL Server 2008 R2, using Visual Studio's 2013.
As a test try to use the SqlConnectionStringBuilder
System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Data Source"] = "(local)";
builder["integrated Security"] = true;
//Or Supply User and Password
builder["Connect Timeout"] = 1000;
builder["Initial Catalog"] = "AdventureWorks;NewValue=Bad";
Console.WriteLine(builder.ConnectionString);
If you do that and are still experiencing the error then move on to testing the networking.
<add name="RM_V1.0CS1" connectionString="Data Source=SERVER;Initial Catalog=DB;User ID=sa;Password=Password" providerName="System.Data.SqlClient" />
Edit Explicitly Set Provider:
For those that might experience similar issues. I save my solutions on a network drive through work. Because I was opening and running my solution from this network location for a reason I'm yet unaware of it was using my windows credentials instead of the SQL credentials that I was passing to the SQL server. Once the solution was moved to my local workstation the method ran as expected. Any insight as to what more specifically was occurring would be of interest.
I have a problem,
private void button_Submit_Click(object sender, EventArgs e)
{
try
{
string connectionString = #"Data Source=Database_TouchPOS.sdf;Persist Security Info=False;";
using (SqlCeConnection connection = new SqlCeConnection(connectionString))
{
using (SqlCeCommand command = connection.CreateCommand())
{
connection.Open();
command.CommandText = "INSERT INTO Product (Title,Price,Category_Id) VALUES (#title, #price,#category_Id)";
command.Parameters.AddWithValue("#title", textBox_Title.Text);
command.Parameters.AddWithValue("#price", textBox_Price.Text);
command.Parameters.AddWithValue("#category_Id", comboBox_Category.SelectedIndex);
command.ExecuteNonQuery();
MessageBox.Show("Product Added Successfully...");
}
connection.Close();
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
Everything seem to be fine, but still can't add data into database.
I did try with complete database path, example c:\project\database.sdf
I did a lot of search before asking. I saw similar problems but not even a single one works for me.
Data are added when compiling but not committed to database. I can see the data after second attempt of debugging.
Please kindly try to explain in detail.
Thanks
You are probably facing this, http://erikej.blogspot.com/2010/05/faq-why-does-my-changes-not-get-saved.html suggest you use a full path to your database file in your connection string.
Did you try to use transactions explicitly?
IDbTransaction transaction = connection.BeginTransaction();
//add to database
transaction.Commit(); // before close connection
This is a very old thread, so I don't know if it will help anyone if I put my answer.
I had this problem, too.
When I executed an update or insert code in C#, apparently, everything was ok, but when I looked up the database, there was no change.
The thing was that while debugging I had the database opened in a Management Studio. And somehow this obstructed the database changes even when there was no error message.
Closing the Management Studio and opening it after executing the code, the changes where perfectly stored in the data base.
Regards.
complete example for those seeking like me... #"Data Source=C:\Users\MYPC\Documents\Visual Studio 2010\Projects\MyProjectFolder\MyProject-1\bin\Debug\MyDatabase.sdf;Persist Security Info=False;";
thank for this example. This saved my day.
While I establish a connection to SQL Server using ADO.NET, it showing errors.
Following is the code:
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=abdul;Integrated Security=true");
SqlCommand cmd = new SqlCommand();
con.Open();
String str="select * from emp where empname='Abdul'";
cmd = new SqlCommand(str, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr == null || !dr.HasRows)
{
MessageBox.Show("No Records found");
}
else
{
while (dr.Read())
{
textBox1.Text = dr[0].ToString();
textBox2.Text = dr[1].ToString();
}
}
When I am running the project it showing the following error:
Cannot open database "abdul" requested by the login. The login failed.
What have to do?
The login is successful at the the SQL Server level. Then either
the database exists but the login you are using doesn't have access to the database
the database doesn't exist
In SSMS, go to adbul database. Expand the security node and add the relevant users (which map to the login) + security there. If you still can't, have you created the database single user?
It's hard to give more details at the moment.
You need to check that the user you are connecting with is a valid SQL Login, and that the password supplied is correct. You also need to ensure the login has an associated SQL User in the database they are trying to connect to.
SQL Logins are used to access the server itself, and they are mapped to database SQL users.
You said you created the database. How did you do this? Was it from sql management studio? If so, was this in the same Windows session as you are executing the program code above?
I ask because if you could create a database, I believe you should be able to connect to it.
I'd look at the difference between successfully connecting with Sql Management Studio and trying to get past the 3rd line of code in your question. (assuming that's where it fails, maybe even edit the question to take out the lines beyond).