I have a generic user (username:user and password:user) that has access to my SQL Database.
So, if I use the following code, I can access to it without problems:
using System.Data.SqlClient;
namespace ConsoleApp1
{
Class Program
{
static void Main(string[] args)
{
string conString = "Data source=server; Initial catalog=db; Integrated security=true";
SqlConnection conn = new SqlConnection(conString);
using (conn)
{
conn.Open();
SqlCommand command = new SqlCommand("SELECT * FROM Table", conn);
SqlDataReader reader = command.ExecuteReader();
conn.Close();
}
}
}
}
However, if I change the conString by replacing IntegratedSecurity=true by User ID=user; Password=user, then I have the exception
System.Data.SqlClient.SqlException:'Login failed for user 'user'.'
I would like to hardcode those credentials so every user without access to the database may use those generic credentials, but I cannot solve that exception.
Related
EDIT: I've just tested it in ASP.NET and it works perfectly fine. So no issue with the connection string or anything. Guess Unity doesn't like this method? Maybe there's some more DLL's I need to copy? Any ideas?
So I'm making a game in Unity and I'm trying to use the System.Data.SqlClient library to connect to some stored procedures I have made for things such as registering a user.
I have copied the System.Data.dll from "C:\Program Files\Unity\Editor\Data\Mono\lib\mono\unity" and that has all worked fine.
I'm currently using this connection string, which works fine on an ASP.NET application but just using a different mdf:
private string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\uppy8\Desktop\Computer Science Project\Mining Game\Assets\MineRace.mdf';Integrated Security = True";
The problem occurs when running this code:
using System.Data.SqlClient;
using System.IO;
public void Login()
{
Crypto crypto = new Crypto();
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
} catch (Exception e)
{
Debug.Log(e);
}
SqlCommand command = new SqlCommand("USERS_LOGIN_USER", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#Username", usernameInputField.text));
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
if (crypto.EncryptString(passwordInputField.text) == reader["password"].ToString())
{
UserAccountManager.instance.userInfo = FetchUserInfo((int)reader["id"]);
}
}
}
}
The problem happens on the line "conn.Open()", where Unity gives me the error:
System.Net.Sockets.SocketException: No such host is known.
Furthermore, without the try catch, the error occurs where I create a new SqlDataReader, where I get this issue:
InvalidOperationException: ExecuteReader requires an open connection to continue. This connection is closed.
I understand that this is an issue with the connection, in that it's not running or the connection isn't working properly, however I can't seem to find a solution and I have a sneaky suspicion that it's something to do with Unity not supporting this library.
Some more clarification just before I end off:
The user enters their credentials into the "usernameInputField" and "passwordInputField"
The user presses Login, which runs the "Login" method shown above
The error occurs.
If any more information is required please leave a comment.
Thanks!
What is the scope of connectionString? Do you need to pass the connectionString to the Login() function?
public void Login(string connectionString)
I am a DBA, not a .Net developer, so forgive me if my questions are too basic or if my .Net syntax is wrong.
You can try this
string connectionString = #"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog ='C:\USERS\uppy8\Desktop\Computer Science Project\Mining Game\Assets\MineRace.mdf'; Integrated Security = True; Connect Timeout = 30; Encrypt = False; TrustServerCertificate = True; ApplicationIntent = ReadWrite; MultiSubnetFailover = False"
SqlConnection con = new SqlConnection();
if (con.State==ConnectionState.Open)
{
con.Close();
con.ConnectionString = connectionString;
con.Open();
cmd.Connection = con;
}
else
{
con.ConnectionString = connectionString;
con.Open();
cmd.Connection = con;
}
I understand the same thing has been asked before and closed due to a simple typo. From what I can see I don't have any typos and I've tried to figure out the problem by Googling but no luck.
I have created this Login Window.
Main Login Window
I have created a local SQL Database from within Visual Studio (2015) to store my users. To establish the connection to this database I have written this line of code in my Enter button that is visible in the Main Login Window.
SqlConnection sqlConn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=C: \USERS\NIKOS\DESKTOP\NIKOS();\SAFE BOX\DATABASE\SAFEBOXDB.MDF;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
This path has been pasted by right clicking my database and selecting properties. In the properties there is a field named Connection String. That's what I have copied and pasted, into the above path in the code.
This is all my code.
//Find path for SQL Connection
SqlConnection sqlConn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=C:\USERS\NIKOS\DESKTOP\NIKOS();\SAFE BOX\DATABASE\SAFEBOXDB.MDF;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
//Add query for actions to be taken once connection is established, select the user
string sqlQuery = "Select * from dbo.Table Where username = '" + txtEnterUserName.Text.Trim() + "' and password = '" + txtEnterPassword.Text.Trim();
//Add SQL Data Adapter passing in the connection and the query
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlQuery, sqlConn);
//Create new Datatable object
DataTable dataTable = new DataTable();
//Fill SQL Data Adapter with the dataTable
sqlDataAdapter.Fill(dataTable);
if (dataTable.Rows.Count == 1)
{
loginMain objFormMain = new loginMain();
this.Hide();
UserDashboard userDash = new UserDashboard();
userDash.Show();
}
else
{
MessageBox.Show("Check Username and Password");
}
When I run the program, my Main Login Window appears as it's the main window, I enter my credentials as per the table in the database and I get this error as soon as I press the "Enter" button.
ArgumentException was unhandled
I have checked and rechecked the path but I can't seem to get it working and I have no idea what the problem is. General Google searches have not helped.
Due to low reputation as I am a new user, I cannot upload my table data, I only have one row with a user name and a password. Presume these are being typed correctly.
The error says that a keyword is not supported. I can't seem to understand this.
EDIT. I have reinstalled the server and the new path is now
using (SqlConnection sqlConn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Nikos\Documents\SafeBox.mdf;Integrated Security=True;Connect Timeout=30"))
as per the new Connection String. So the new code for the Enter button is now
private void enterButton_Click(object sender, EventArgs e)
{
string sqlQuery = #"Select * from dbo.Table
Where username = #user AND
password = #pass";
using (SqlConnection sqlConn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Nikos\Documents\SafeBox.mdf;Integrated Security=True;Connect Timeout=30"))
using (SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn))
{
sqlConn.Open();
cmd.Parameters.Add("#user", SqlDbType.NVarChar).Value = txtEnterUserName.Text.Trim();
cmd.Parameters.Add("#pass", SqlDbType.NVarChar).Value = txtEnterPassword.Text.Trim();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
loginMain objFormMain = new loginMain();
this.Hide();
UserDashboard userDash = new UserDashboard();
userDash.Show();
}
else
{
MessageBox.Show("Check Username and Password");
}
}
}
}
The new error I have is {"Incorrect syntax near the keyword 'Table'."} and the error points to this line.
using (SqlDataReader reader = cmd.ExecuteReader())
There are many errors in your code.
The first one is the space between the C: drive letter and the remaining path is wrong and should be removed. Also adding a semicolon in the middle of the connection string as part of the path confuses the connectionstring parser that uses the semicolon as separator between keys and values. This is the origin of the error message because after the NIKOS(); semicolon the parser ends its discover of the path and tries to make sense of \SAFE BOX.... as it was a key to parse.
You should remove it from your disk path and adjust your connectionstring
SqlConnection sqlConn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;
Initial Catalog=C:\USERS\NIKOS\DESKTOP\NIKOS\SAFE BOX\DATABASE\SAFEBOXDB.MDF;
Integrated Security=True;
Connect Timeout=30;
Encrypt=False;
TrustServerCertificate=True;
ApplicationIntent=ReadWrite;
MultiSubnetFailover=False");
Now the problems in code are even worse
string sqlQuery = #"Select * from [Table]
Where username = #user AND
password = #pass";
using(SqlConnection sqlConn = new SqlConnection(....))
using(SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn))
{
sqlConn.Open();
cmd.Parameters.Add("#user", SqlDbType.NVarChar).Value = txtEnterUserName.Text.Trim();
cmd.Parameters.Add("#pass", SqlDbType.NVarChar).Value = txtEnterPassword.Text.Trim();
using(SqlDataReader reader = cmd.ExecuteReader())
{
if(reader.HasRows)
{
loginMain objFormMain = new loginMain();
this.Hide();
UserDashboard userDash = new UserDashboard();
userDash.Show();
}
else
{
MessageBox.Show("Check Username and Password");
}
}
}
First of all, you don't need a complex SqlDataAdapter if you just want to check if the user exists or not. A simple SqlCommand with an SqlDataReader will do just fine.
Second, all disposable objects should go inside an using statement to be sure that when you have finished to use them, they will be destroyed also in case of exceptions.
Finally, parameters are always the way to go when you need to pass values to your database. Failing to use them will lead to Sql Injection attacks or unexpected syntax errors when your strings contains single quotes.
So i was trying to connect a c# gui app to a xampp sql server here's the code:
try
{
string connectionString = "Server = localhost:8080; database = blog; Uid=root;Pwd";
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("insert into logins(username,password) values('name','password')", conn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
this is the code username is root and no password
but when the program starts it raises an exception saying:
Format of the initialization string does not conform to specification starting at index 52.
Whats causing this problem and how can i solve it?
Thanks in advance
SQLConnection class is used to connect to sqlserver and to Connect Mysql MySqlConnection will be used
you need to add MySql Library in your C# project.
using MySql.Data.MySqlClient;
Config
string myConnectionString = "server=localhost;database=testDB;uid=root;pwd=pwd;";
Use
string connetionString =""; //get from config;
MySqlConnection cnn ;
cnn = new MySqlConnection(connetionString);
IS it possible to execute a raw SQL command of any type (SELECT, UPDATE, DELETE....) in C#. I am looking to add a feature similar to the SQL Server Management Studio query window where I can just type in any SQL command and it executes it. In my case I am not worried about sql injection, I know this risk with this feature. All the connection parameters are passed to me (I have a valid connection string), but I know nothing about the database itself. The SQL command is also syntactically correct before I get the command. I cannot seem to find a solution that will work in all cases, probably just overlooking the obvious solution.
Here is an ADO example for you
using System;
using System.Data;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString =
"Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=true";
// Provide the query string with a parameter placeholder.
string queryString =
"UPDATE [dbo].[USR_Users] SET [Active] = 1 WHERE Id = 1";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
You can simply use ADO .NET and show the results of the query if it executed successfully or not, just put the following code in the event handler when you want to execute your query:
using (SqlConnection conn = ConnectionClass.GetInstance().Connection())
using (SqlCommand cmd = new SqlCommand(TextBoxQuery.Text, conn))
{
conn.Open();
TextBoxNoOfRowEffected.Text = cmd.ExecuteNonQuery().ToString();
}
SqlCommand.ExecuteNonQuery() Documentation
When I try to write in C# a connection to my app to my database, I build the application successfully in Visual Studio 2005 but when I run the site in debugger i get an error:
Exception Details: System.ArgumentException: Format of the initialization string does not conform to specification starting at index 118.
Here is the connection code that is giving the error:
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Server"].ConnectionString);
I have the connection string written correctly in my web.config, file so im clueless on what this remotely means. Im not sure if im missing anything. Any help appreciated. Here is my entire code for the section that might help:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
using System.Data.SqlClient;
public partial class RateAnalyzerPage: System.Web.UI.Page
{
protected void Search_Click(object sender, EventArgs e)
{
string IDnumber = mechantNumber.Text;
string selectSQL = "SELECT FROM Authors Where MID='"+ IDnumber +"'";
// SqlConnection con = new SqlConnection(#"Server=");
//SqlConnection con = new SqlConnection();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Server"].ConnectionString);
SqlDataReader reader;
try
{
con.Open();
SqlCommand cmd = new SqlCommand(selectSQL, con);
reader = cmd.ExecuteReader();
while (reader.Read())
{
QualVol.Text = reader["TotalVolume"].ToString();
}
reader.Close();
}
catch (Exception err)
{
}
finally
{
con.Close();
}
}
}
Let me know if im missing some data that would help.
Heres the connection string:
I've separated out and XML decoded the connection string value:
Data Source=Server;Initial Catalog=Odata;Integrated Security=True;MultipleActiveResultSets=False;Packet Size=4096;Application Name="Microsoft SQL Server Management Studio"User ID=Name;Password=PW
As you can see, you're missing a ; between Application Name and User ID. I'm not sure if that's the issue, but it's possible.
Your connection string use the Integrated Security=True, but the right syntax is
Integrated Security=SSPI; or Trusted_Connection=True so change it and remove the UserId and Password.
(or remove Integrated Security=True and leave UserID and Password)
Try to change something in your code.
protected void Search_Click(object sender, EventArgs e)
{
string IDnumber = mechantNumber.Text;
string selectSQL = "SELECT * FROM Authors Where MID=#num";
using(SqlConnection con = new SqlConnection
(System.Configuration.ConfigurationManager.ConnectionStrings
["Server"].ConnectionString))
{
SqlDataReader reader;
con.Open();
SqlCommand cmd = new SqlCommand(selectSQL, con);
cmd.Parameters.AddWithValue("#num", IDNumber);
reader = cmd.ExecuteReader();
while (reader.Read())
{
QualVol.Text = reader["TotalVolume"].ToString();
}
reader.Close();
}
}
Try to use the using statemend, this guarantees the disposing of your connection
Try to use parametrized query, this avoid Sql Injection attacks and quoting problems
Also SELECT requires a fields list or *
I think Jacob has it right. On a side note, don't do this:
string selectSQL = "SELECT FROM Authors Where MID='"+ IDnumber +"'";
This will lead to sql injection attacks, just like the one that was used to get yahoo user accounts last week.
Do this instead:
string selectSQL = "SELECT * FROM Authors Where MID=#ID";
cmd.Parameters.AddWithValue("#ID", IDnumber );