SQL exception was unhandled by user code on connection open - c#

i am beginner to microsoft asp.net and i got An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code error when trying to select value from Microsoft visual studio database. The error was on the con.Open() line
Below is my code:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C: \Users\Ng\Documents\Visual Studio 2015\Projects\Assignment6\Assignment6\App_Data\photoCompetition.mdf;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework");
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM User WHERE email=#username and password=#word", con);
cmd.Parameters.AddWithValue("#username", emailtext.Text);
cmd.Parameters.AddWithValue("#word", passwordtext.Text);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
int i = cmd.ExecuteNonQuery();
con.Close();
if (dt.Rows.Count > 0)
{
Response.Redirect("Default.aspx");
}
else
{
lblMsg.Text = "Your username and word is incorrect";
lblMsg.ForeColor = System.Drawing.Color.Red;
}
}

So your first issue is that you had a space in your Sql Connection string.
C: \Users\Ng\Documents\Visual Studio 2015\Projects\Assignment6\Assignment6\App_Data\photoCompetit‌​ion.mdf
Now since your query looks valid and assuming the tables and columns exists, you are having a problem with the SQL query you are trying to execute. I see two options here.
Enclose your parameters with a single quote to denote it as a string
SqlCommand cmd = new SqlCommand("SELECT * FROM User WHERE email='#username' and password='#word'", con);
Use SqlParameterCollection.Add Method (String, SqlDbType, Int32).
cmd.Parameters.Add("#username", SqlDbType.Text).Value = emailtext.Text;
cmd.Parameters.Add("#word", SqlDbType.Text).Value = passwordtext.Text;
Also, don't forget to close your SqlConnection with con.Close();

Related

System.Data.SqlClient.SqlException: 'Incorrect syntax near '`'.'

I'm trying to create a login field using ASP.NET which will take input from the textbox fields and check them against the "user" table in my database. The columns are User ID and Password. But an error
System.Data.SqlClient.SqlException: 'Incorrect syntax near '`'
appears when the login form is used. I don't see any issue with the syntax...
I'm new to this so please excuse me if the error is obvious!
public partial class Login_Page : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblErrorMessage.Visible = false;
SqlConnection con = new SqlConnection("Data Source=JACKS-PC\\SQLEXPRESS;Initial Catalog=CBR;Integrated Security=True");
con.Open();
}
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=JACKS-PC\\SQLEXPRESS;Initial Catalog=CBR;Integrated Security=True";
con.Open();
string userid = txtUsername.Text.Trim();
string password = txtPassword.Text.Trim();
SqlCommand cmd = new SqlCommand("select `user id`,`password` from user where `user id`='" + txtUsername.Text + "'and `password`='" + txtPassword.Text + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Session["username"] = txtUsername.Text.Trim();
Response.Redirect("Homepage.aspx");
}
else
{
lblErrorMessage.Visible = true;
}
con.Close();
}
}
Just remove the '`' characters to make it work.
Your code is vulnerable to injection try to add values with SqlCommand.Parameters.Add() method.
Use this code:
SqlCommand cmd = new SqlCommand("select userid, password from user where user id = #id and password = #password", con);
cmd.Parameters.Add("#id", SqlDbType.VarChar).Value = txtUsername.Text;
cmd.Parameters.Add("#password", SqlDbType.VarChar).Value = txtPassword.Text;
And as #marc_s mentioned, user id is not a valid column name, it should be like userid or if it has space in it is should be like: [user id]
there are many issues with your code :
Do not store plain text password in your program or app config.
Do not embed connection string into your program
` is not SQL Server Syntax.
never use string concatenation in your queries specifically if inputs are coming from users. Use Parameterized queries.
.
using (SqlCommand cmd = new SqlCommand("select 1 from tbl where id=#id", conn))
{
var idParameter = new SqlParameter()
idParameter.ParameterName = "#id";
idParameter.Value = 1234;
cmd.Parameters.Add(idParameter);
....
}
always dispose objects when you finish your work with them. For this use using(SqlConnection conn = new SqlConnection()).
all methods which implements IDisposable can be used within using statement

Search sql server database server using Textbox and button in C#

So I am using MS visual studio to create an application in c# that will pull information from a sql server database.
I have created a textbox and a button to search my gridview. I am using a stored procedure that searched multiple rows to pull information from my Sql Database.
I am having trouble with my aspx.cs code. I have tried so many different ways to create a searchbox but haven't had any luck yet
Here is my code for my search button.
I am getting the error-
"Input string was not in a correct format."
this error is on the line cmd.ExecuteNonQuery();
Help is much appreciated, thank you.
protected void Button_srch_invest1_Click(object sender, EventArgs e)
{
string connectionStr = ConfigurationManager.ConnectionStrings["ORAProjectConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionStr))
{
string find = "sp_SrcProtocols";
SqlCommand cmd = new SqlCommand(find, con);
cmd.Parameters.Add("#ORAID", SqlDbType.Int).Value = TextBox_Srch.Text;
cmd.Parameters.Add("#InvestLastName", SqlDbType.NVarChar).Value = TextBox_Srch.Text;
cmd.Parameters.Add("#ManagerLastName", SqlDbType.NVarChar).Value = TextBox_Srch.Text;
con.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, "ORAID");
da.Fill(ds, "InvestLastName");
da.Fill(ds, "ManagerLastName");
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
}
By default, a SqlCommand expects a query, not a stored procedure's name. You have to set the command type before executing it.
cmd.CommandType = CommandType.StoredProcedure;
It seems, you are passing same text box value (TextBox_Srch.Text) to all 3 parameters. And first parameter #ORAID is expecting integer value and you might be passing text. So it's causing SQL server to raise below error.
Input string was not in a correct format.
This is what worked (and i changed my sql to just accept one parameter #search)
protected void Button_srch_invest1_Click(object sender, EventArgs e)
{
string connectionStr = ConfigurationManager.ConnectionStrings["ORAProjectConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionStr))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "sp_SrcProtocols";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#search", SqlDbType.NVarChar).Value = TextBox_Srch.Text;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
con.Close();
}
}

Error :An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

I am programming an application with C# and SQL Server and I want to to connect to my database and display the result of a search query and I tried many methods, dataset and reader, but the same error always shows up - please help me!
The error:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Syntaxe incorrecte vers '1012'.
Here is the code part (med_ID is the name of textbox, dgrAffich_tab is a dataGridView):
private void button1_Click(object sender, EventArgs e)
{
int ID;
ID = int.Parse(med_ID.Text);
SqlConnection conn = new SqlConnection(#"Data Source=DESKTOP-HCLRURF\SQLEXPRESS;Initial Catalog=ydb;Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT Quantite FROM TabRestitue WHERE Tab_medID= %" + ID + "% ORDER BY DateDePeremption ASC ");
conn.Open();
cmd.Connection = conn;
DataSet dt = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
dgrAffich_tab.DataSource = dt;
conn.Close();
}
Your Sql command has an syntax error, the 1012 the error is referencing is your med_Id value.
A string, in SQL, must be encapsulated between single quote (')
The Sql Server currently receive this string (there's no quote around %1012%)
SELECT Quantite FROM TabRestitue WHERE Tab_medID= %1012% ORDER BY DateDePeremption ASC
The valid Sql would be
SELECT Quantite FROM TabRestitue WHERE Tab_medID='%1012%' ORDER BY DateDePeremption ASC
But the way your are doing it is unsafe because of Sql Injection. The recommended way would be to use SqlParameter. Also, SqlConnection, SqlCommand and SqlDataAdapter are disposable, so i've added a using to dispose them.
int ID;
ID = int.Parse(med_ID.Text);
using (SqlConnection conn = new SqlConnection(#"Data Source=DESKTOP-HCLRURF\SQLEXPRESS;Initial Catalog=ydb;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand("SELECT Quantite FROM TabRestitue WHERE Tab_medID= #medId ORDER BY DateDePeremption ASC "))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#medId", "%" + ID + "%");
conn.Open();
cmd.Connection = conn;
DataSet dt = new DataSet();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
}
dgrAffich_tab.DataSource = dt;
conn.Close();
}
}
To avoid errors, build the LIKE expression as a string in T-SQL and use a strongly-typed parameterized query.
SqlCommand cmd = new SqlCommand("SELECT Quantite FROM TabRestitue WHERE Tab_medID= '%' + CAST(#ID AS varchar(10)) + '%' ORDER BY DateDePeremption ASC;");
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = ID;

how to update 'datetime' in column after login

I have a table name is 'User_tbl' where i am saving data of all registered users and the same table is being used to verify the users during Login.
I want to update only 'LastSeen' column with current datetime after login.
Look at this picture.
code behind
protected void Submit(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from User_tbl where UserName =#username and Password=#password", con);
cmd.Parameters.AddWithValue("#username", txtUserName.Text);
cmd.Parameters.AddWithValue("#password", txtPWD.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
//to define the user seesion (starting user session)
Session["username"] = txtUserName.Text;
Response.Redirect("default2.aspx");
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "LoginValidate", "<script language='javascript'> document.getElementById('errorMessage').innerHTML = 'Invalid Username or Password'</script>");
}
}
Do you mean something like this?
SqlConnection sqlConn = new SqlConnection(connection string here);
SqlCommand sqlComm = new SqlCommand();
sqlComm = sqlConn.CreateCommand();
sqlComm.CommandText = #"UPDATE User_tbl SET LastSeen=GetDate() WHERE UserName='#userName'";
sqlComm.Parameters.Add("#userName", SqlDbType.VarChar);
sqlComm.Parameters["#userName"].Value = txtUserName.Text;
sqlConn.Open();
sqlComm.ExecuteNonQuery();
sqlConn.Close();
You'd need to place something along those lines in your 'if (dt.Rows.Count > 0)' code.
You may wish to reuse the same connection that you created for your SELECT statement.
Many other options are available. Often this sort of thing is best achieved using a stored procedure, where you can check the login credentials and perform any related updates in a single request to the database server.

ADO select statement with full text search with SQL injection

The database that I am connecting to has a table with a Full Text Search index. This works correctly.
select * from MyTable where contains(*, 'value')
In WPF if I send that exact command down it works. However value is not hard coded it is something an user types in so it needs to be protected for SQL injection. The issue is that in doing so it does not return results. Here is my code;
DataTable dt = new DataTable();
string ConString = "Data Source=127.0.0.1,1433;Initial Catalog=MyDB;User Id=sa;Password=amazingSecurePassword;";
using (SqlConnection con = new SqlConnection(ConString))
{
string sqlCMD = "select * from MyTable where contains(*, #s1)"
SqlCommand cmd = new SqlCommand(sqlCMD, con);
SqlDataAdapter da = new SqlDataAdapter();
try
{
con.Open();
cmd = new SqlCommand(sqlCMD, con);
cmd.Parameters.Add(new SqlParameter("#s1", "value"));
da.SelectCommand = cmd;
da.Fill(dt);
con.Close();
}
catch (Exception x)
{
//Error logic
}
finally
{
cmd.Dispose();
con.Close();
}
}
Edit: #Mike comment worked. Change the SqlDbType.NVarChar fixed the issue
As noted in the above comment, setting the SQlDbType to NVarChar during the creation of the SqlParameter helps the CLR determine the right data type. More info about the SqlParameter constructor at MSDN.

Categories

Resources