I am trying to pass parameters from my program to Stored Procedure in EXEC format.Following is my code
public void button1_Click(object sender, EventArgs e)
{
frm = new FrmLogin();
OleDbConnection conn = new OleDbConnection("File Name=E:\\Vivek\\License Manager\\License Manager\\login.udl");
try
{
conn.Open();
string user = username.Text;
string pass = password.Text;
string query = "EXEC dbo.checkuser"' + username.Text'" + " " + "'password.Text'"";
OleDbCommand cmd = new OleDbCommand(query,conn);
cmd.ExecuteNonQuery();
// Retrieve the return value
string result = query.ToString();
MessageBox.Show(result);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
conn.Close();
}
What should I write in string query=" "?,I am trying to pass username and password as parameters to the stored procedure and once the query executes and returns the result ,I will store it in another variable named result.Am I doing it the right way? I am new to C#
Please suggest,
Thanks
Building command text with dynamically inserted segments from user input is very dangerous, and leaves you open to SQL Injection.
Below is a slight variation which parameterizes those strings. This approach is much safer.
string query = "dbo.checkuser";
OleDbCommand cmd = new OleDbCommand(query,conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#username", username.Text);
cmd.Parameters.AddWithValue("#password", password.Text);
Note: This updated version sets up the command as a stored procedure, instead of plain text.
try this
OleDbCommand cmd = new OleDbCommand("StoredPorcedureName",conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameter.AddWithValue("#user", username.Text);
cmd.Parameter.AddWithValue("#pwd", password.Text);
cmd.ExecuteNonQuery();
That looks Okay at a glance except for your query string. Change to:
string query = "EXEC dbo.checkuser '" + username.Text "', '" + password.Text + "'";
might work better.
Edit
Yes, as per comments about SQL injection, Troy's answer is significantly better.
Just for completeness that can be possibly used in other situations, you can avoid SQL injection using this method by trying something like:
string query = "EXEC dbo.checkuser '" + username.Text.Replace("'", "''") "', '" + password.Text.Replace("'", "''") + "'";
Related
I have created a simple application every thing is working fine except update
portion insertion is working fine with same table data
My code is
private void button2_Click(object sender, EventArgs e)
{
string cmd = ("UPDATE submissionFee SET [stdName]='" + textBox2.Text + "', [fatherName]='" + textBox3.Text + "', [program]='" + textBox4.Text + "', [adress]='" + textBox5.Text + "',[email]='" + textBox6.Text + "', [cellNum]='" + textBox7.Text + "', [isPaid] = '" + textBox8.Text + "', [SubmissionDate] = '" + dateTimePicker1.Value.ToString("MM/dd/yyyy") + "'Where [ID]='" + textBox1.Text + "'");
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = cmd;
command.ExecuteNonQuery();
MessageBox.Show("Account Has Been Updated");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
MessageBox.Show("Please Enter Valid Data");
}
}
Error Screenshot
Probably the connection is already open when you try to open it.
Either:
1) Make sure you close the connection from the last time you used it.
2) Or, if it is sometimes supposed to be kept open, check if the connection is already open, and don't close it if it is. Something like:
bool bWasOpen = (connnection.State == ConnectionState.Open);
if (!bWasOpen)
connection.Open();
...
if (!bWasOpen)
connection.Close();
Much Worse than the crash: Your code is volunerable to Sql-injection.
--> Use parameterized sql.
The reason for this exception in the dialog is due to the connection state is already open; and hence it cannot be opened again. You must close the connection in your previous statement. Or, check if the connection closed, and then open it.
Some other tips to you is
Do not use Textbox1, Textbox2 etc., give them proper ID like txtStudentId, txtFatherName etc.,
User SQL Parameters to pass the values to your database. check the sample statements below
String query = "UPDATE submissionFee SET stdName=#stdName, fatherName=#fatherName where id=#id;";
SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("#id",txtID.txt); command.Parameters.Add("#stdName",txtStudent.Text); command.Parameters.Add("#fatherName",txtFatherName.Text);
command.ExecuteNonQuery();
Please use using statement when You query to database.
Why? Simple... it has implemented IDisposable.
P.S.
Use parameterized query to protect against SQL Injection attacks.
string insertStatement = UPDATE submissionFee SET stdName=#stdName,fatherName=#fatherName,program=#program,adress=#adress,email=#email,cellNum=#cellNum,isPaid=#isPaid,SubmissionDate=#SubmissionDate,ID=#ID
using (OleDbConnection connection = new OleDbConnection(connectionString))
using (OleDbCommand command = new OleDbCommand(insertStatement, connection))
command.Parameters.AddWithValue("#ID",textBox1.Text);
command.Parameters.AddWithValue("#stdname",textbox2.Text);
command.Parameters.AddWithValue("#fathername",textBox3.Text);
command.Parameters.AddWithValue("#program",textBox4.Text);
command.Parameters.AddWithValue("#adress",textBox5.Text);
command.Parameters.AddWithValue("#email",textBox6.Text);
command.Parameters.AddWithValue("cellNum",textBox7.Text);
command.Parameters.AddWithValue("#isPaid",textBox8.Text);
command.Parameters.AddWithValue("#SubmissionDate",dateTimePicker1.Value.ToString("MM/dd/yyyy"));
connection.Open();
var results = command.ExecuteNonReader();
}
}
Part of code was taken from this link.
I have a datagrid setup in my windows form in Visual Studio. The datagrid is updated from the textboxes but I can't get it to edit the values held in the database.
This is the code I am using:
private void btnUpdate_Click(object sender, EventArgs e)
{
string constring = "datasource=localhost;port=3306;username=root;password=admin";
string Query = "UPDATE database.taxi SET PickupLocation='" + txtPickupLocation.Text + "',PickupArea='" + comboBxPickupArea.Text + "',PickupTime='" + dateTimePickup.Text + "',DestinationLocation'" + txtDestinationLocation.Text + "',DestinationArea='" + comboBxDestinationArea.Text + "',Name'" + txtCustomerName.Text + "',Address='" + txtCustomerAddress.Text + "',Tour='" + comboBxTour.Text + "',VehicleRegistration='" + txtvehicleregistration.Text + "' ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("Entry has been updated");
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
But I get the error:
"You have an error in your SQL syntax; check the manual that
corresponds to your SQL server version for the right syntax to use
near '"DestinationLocation'"......... "
Any help would be appreciated.
You forget to use = after your DestinationLocation and Name
Change your
DestinationLocation'" + txtDestinationLocation.Text
and
Name'" + txtCustomerName.Text + "'
to
DestinationLocation = '" + txtDestinationLocation.Text
and
Name = '" + txtCustomerName.Text + "'
But please don't use string concatenation in your sql queries. Use parameterized queries instead. This kind of string concatenations are open for SQL Injection attacks.
Also you don't need to use ExecuteReader since your query doesn't return anything. Use ExecuteNonQuery instead.
As a full code;
string Query = "UPDATE database.taxi SET PickupLocation=#PickupLocation, PickupArea=#PickupArea, PickupTime=#PickupTime, DestinationLocation=#DestinationLocation,
DestinationArea=#DestinationArea, Name=#Name, Address#Address, Tour=#Tour, VehicleRegistration=#VehicleRegistration";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
cmdDataBase.Parameters.AddWithValue("#PickupLocation", txtPickupLocation.Text);
cmdDataBase.Parameters.AddWithValue("#PickupArea", comboBxPickupArea.Text);
....
....
cmdDataBase.ExecuteNonQuery();
You need an equals sign after DestinationLocation in your SQL.
Incidentally, you probably don't want to use ExecuteReader, since you're not returning any values (and aren't interested in any.) Try ExecuteNonQuery.
ETA: and Soner Gönül is absolutely right about the need for parameterized queries rather than string concatenation!
Finally, I assume that you aren't going to hard-code your connection string in your final version?
I am trying to make a simple login page, user enters ID and password, and chooses role from a dropdown list:Student, Administrator or Instructor. Here is the code:
protected void loginButton_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=University;Integrated Security=True;Pooling=False";
//myConn.Open();
//string strqry = "Insert into students values (" + TextBox1.Text +
//",'" + TextBox2.Text + "','" + TextBox3.Text + "')";
//SqlCommand myCom = new SqlCommand(strqry, myConn);
//int numrow = myCom.ExecuteNonQuery();
//myConn.Close();
Int32 verify;
string query1 = "Select count(*) from Login where ID='" + idBox.Text + "' and Password='" + passwordBox.Text + "' and Type='"+ LoginAs.Text +"'" ;
SqlCommand cmd1 = new SqlCommand(query1, con);
con.Open();
verify = Convert.ToInt32(cmd1.ExecuteScalar());
con.Close();
if (verify > 0)
{
Response.Redirect("succesful.aspx");
}
else
{
Response.Redirect("unsuccesful.aspx",true);
}
}
The problem is, when i try without checking the value of the dropdown list called "LoginAs", it works fine and makes validation. But when i also check the Type, which is either Student, Administrator or Instructor it always makes unsuccesful login even though all the information is correct. Can anyone help me to find what is wrong?
Thanks
use parametrized queries maybe it will be resolved and you would prevent risks it goes like this
cmd1.Parameters.AddWithValue("#ID", idBox.Text);
The first points to check is the:
The all of the letters should has the same case.
The role should be truncated in database and in the application
But, it's preffered to use enum/int to define role of user instead of a text name.
Give a try to SqlDataReader class. You can catch if an reads occur.
Here is the link. While this not the case I recommend you to use a scalar function in your database or use EntityFramework or other ORM tools.
I am Working in ASP.NET and SqlServer.
I have two textboxes with calender extender in my application where user will select two dates.I want to get data between those two dates from sqlserver where my datatype for that particular field is DateTime. please tell me how to proceed with this ...I wrote a query but thats not working..
my query:
SqlCommand cmd = new SqlCommand("select top 1 OrderNumber from tblOrderMaster where OrderedDate>='" + txtfromcal.Text + "' and OrderedDate<='" + txttocal.Text + "' ", conn);
things to do
parameterized the query to prevent from sql injection
use using statement to properly dispose the object
use try-catch block to handle excpetion
eg,
string query = #"select top 1 OrderNumber
from tblOrderMaster
where OrderedDate BETWEEN #startDate AND #endDate";
using(SqlConnection conn = new SqlConnection("connectionString here"))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#startDate", txtfromcal.Text);
cmd.Parameters.AddWithValue("#endDate", txttocal.Text);
try
{
conn.Open();
// other codes
// to fetch the record
}
catch(SqlException e)
{
// do something with
// e.ToString()
}
}
}
SOURCES
AddWithValue Method
Add (recommended method to be used)
use this code:
Sqlcommand cmd=new sql command ("Select data from tablename
where date>=startdate
and date<=enddate",connection)
Try this
SELECT * FROM YourTableName WHERE sqlDateColumnName BETWEEN '" + textbox1.Text + "' AND '" + textbox2.Text + "'
If you please help me out i have an error in my code that i can not understand it.
the error is:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near 'Login'.
and my code:
public static void ChangePassword(string login, string password)
{
var sqlCon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string query = #"update Organizer set Password ="+ password + "where Login=" + login + "";
SqlCommand cmd = new SqlCommand(query, sqlCon);
cmd.CommandType = CommandType.Text;
try
{
sqlCon.Open();
cmd.ExecuteNonQuery();
sqlCon.Close();
}
catch (Exception ee) { throw ee; }
}
We've seen enough sql injection attacks, we don't need another one, please fix your code and use parameters.
Use using blocks to avoid leaking connections.
Install an exception handler like ELMAH.
Don't save passwords in the database
using (var sqlCon = new SqlConnection(...))
{
string query = #"update Organizer set Password =#password where Login=#login";
SqlCommand cmd = new SqlCommand(query, sqlCon);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#password", SqlDbType.VarChar, 8000);
cmd.Parameters["#password"].Value = password;
cmd.Parameters.Add("#login", SqlDbType.VarChar, 8000);
cmd.Parameters["#login"].Value = login;
sqlCon.Open();
cmd.ExecuteNonQuery();
sqlCon.Close();
}
Try
string query = #"update Organizer set Password ='"+ password + "' where Login= '" + login + "'";
You are missing the ' around string, that being said you are likely very open to sql injection attacks ( Im guessing because of the code, and lack of a clearing function).
Also make sure your not storing passwords in plain text :)
The ' is used like " in sql.
If you were going to use the code above, your issue is that you're not wrapping the new password or login in single quotes:
string query =
#"update Organizer set Password = '" +
password +
"' where Login= '" + login + "'";
But I wouldn't use that code at all. It's quite dangerous since it allows people to pass in arbitrary SQL. I would use parameterized queries instead:
var query = "update organizer set password = #password where login = #login";
var command = new SqlCommand(query, sqlCon);
command.Parameters.Add("#password", SqlDbType.VarChar, 100, password);
command.Parameters.Add("#login", SqlDbType.VarChar, 100, login);
You need single quotes...
set Password = ' /*<---*/ "+ password + "' /*<---*/ where Login=' /*<---*/ " + login + "' /*<---*/ "