I keep getting this run time error, syntax error in from clause. I tried already using my sql query in access and it seems ok.
Here's my code and I am using C# windows form with text box and button
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Misry27\Documents\Visual Studio 2010\Projects\Inventory\Inventory\bin\Debug\Inventory.mdb");
OleDbCommand cmd = new OleDbCommand("select * from Employee where username = '" + this.tbUsername.Text + "' and password = '" + this.tbPassword.Text + "';", conn);
OleDbDataReader dr;
conn.Open();
dr = cmd.ExecuteReader();
int count = 0;
while (dr.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Username or Password is correct");
}
else
{
MessageBox.Show("Username or Password Incorrect");
}
conn.Close();
As explained in the comments above, PASSWORD is a reserved keyword and need to be enclosed in square brackets when used in query executed from net.
The usual advice follows. Use parameterized query to avoid parsing problem and sql injections, use the using statement around your disposable objects.
using(OleDbConnection conn = new OleDbConnection(a correct connection string here))
using(OleDbCommand cmd = new OleDbCommand(#"select * from Employee
where username = ? AND [Password] = ?", conn);
{
conn.Open();
cmd.Parameters.AddWithValue("#p1", this.tbUsername.Text);
cmd.Parameters.AddWithValue("#p2", this.tbPassword.Text);
using(OleDbDataReader dr = cmd.ExecuteReader())
{
.....
}
}
Related
This question already has answers here:
What are good ways to prevent SQL injection? [duplicate]
(4 answers)
Closed 4 years ago.
I have been doing simple website using ASP, but am not sure how to add parameterised query to avoid any SQL Injection attacks, can anybody help me to do it i always encounter errors and it has been more than a week that am doing and still i can't figured out. below i attached my simple code.
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string sql = "Select * From Users Where UserID='" + txtUser.Text + "' And Password='" + txtPwd.Text + "'";
con.Open();//opens the connection
//create the command object
cmd = new SqlCommand(sql, con);
//assigns the result to the reader
dr = cmd.ExecuteReader();
dr.Read();//read the record's data
//if there's a matching record found
if (dr.HasRows)
{
if (dr["UserType"].Equals("admin"))
{
Response.Redirect("dhome.aspx");
}
else if (dr["UserType"].Equals("staff"))
{
Response.Redirect("shome.aspx");
}
else if (dr["UserType"].Equals("member"))
{
Response.Redirect("mhome.aspx");
}
}
else
{
lblAlert.Text = "Invalid username or password!";
}
dr.Close(); //close the data reader
con.Close();//close the connection //declaration of data access components
}
You should add them using SqlCommand.Parameters.Add():
using (SqlConnection con = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand("Select * From Users Where UserID=#username And Password=#password", con);
cmd.Parameters.Add("#username", SqlDbType.VarChar).Value = username;
cmd.Parameters.Add("#password", SqlDbType.VarChar).Value = password;
//rest of the code ...
}
You need to use SqlCommand.Parameters.Add. You should also implement dispose (via using blocks or calling Dispose) to release resources after use:
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string sql = "Select * From Users Where UserID=#user And Password=#pwd";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#user", SqlDbType.VarChar);
command.Parameters["#user"].Value = "value";
command.Parameters.Add("#pwd", SqlDbType.VarChar);
command.Parameters["#pwd"].Value = "value";
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
// read row
}
}
}
I am implementing an online voting system for my school-project.
After the voter's log-in, i want to display their name, and ID in the label control at the content body. I try to use SESSION to store the voter's username in the log-in page but I'm not sure of my syntax because nothings happen.
I want to know the other way of retrieving a data from database! Please teach me.
public void GetInformation()
{
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;
cmd.CommandText = "SELECT * FROM tblUsers WHERE voter_name = '" + Session["VotersID"] + "'";
OleDbDataReader reader = cmd.ExecuteReader();
if(reader.Read())
{
lblVoterName.Text = reader["usr_FirstN"].ToString() + " " + reader["usr_LastN"].ToString();
}
}
Please Help Me. Thanks! -
#Honey Maglangit , what you use is PARAMETER not SESSION.
Response.Redirect("VoterPage.aspx?VotersID="+VoterUsername.Text);
So, you should get your VotersID by this way:
public void GetInformation()
{
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;
cmd.CommandText = "SELECT * FROM tblUsers WHERE voter_name = '" + Request.QueryString["VotersID"].ToString() + "'";
OleDbDataReader reader = cmd.ExecuteReader();
if(reader.Read())
{
lblVoterName.Text = reader["usr_FirstN"].ToString() + " " + reader["usr_LastN"].ToString();
}
}
Try it again.
You can use LogonUserIdentity as follow
if (Request.LogonUserIdentity.IsAuthenticated)
lblName.Text = Request.LogonUserIdentity.Name;
just add this namespace:
using Microsoft.AspNet.Identity;
then you can get LoggedInUserId by:
User.Identity.GetUserId();
Or
HttpContext.Current.User.Identity.GetUserId();
So you don't need to use session to keep UserId.
Also you can create Custom Identity and instead of save Username in Name property, storing custom string Store User Data in ASP.NET Identity
get session data and send to one page(register.aspx) to another page(user_home.aspx)
Session["remail2"] = txtemailsignin.Text;
Server.Transfer("user_home.aspx", true);
display the user-information after logging
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["socailweb"].ConnectionString);
string sql = "select * from tblUsers where remail='" + Session["remail2"] + "'";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader sqldr = cmd.ExecuteReader();
if (sqldr.Read() == true)
{
lblVotersID.Text = sqldr.GetValue(2).ToString();
lblVoterName.Text = sqldr.GetValue(3).ToString();
}
sqldr.Close();
con.Close();
I am trying to add records into my C# project and it runs with no errors but it doesn't add anything in the database:
private void saveBtn_Click(object sender, EventArgs e)
{
if (admNo.Text != "" & session.Text != "" & name.Text != "")
{
SqlConnection cn = new SqlConnection("Data Source=C:\\Users\\Divya Pathak\\Documents\\Visual Studio 2012\\Projects\\SchoolRecord\\SchoolRecord\\Database1.sdf");
SqlCommand cmd = new SqlCommand();
cn.Open();
cmd.CommandText = "insert into addNew (no,session,name) values ('" + admNo.Text + "', '" + session.Text + "', '" + name.Text + "')";
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Record inserted successfully", "mission successfull");
}
}
Could someone please advise why?
you need to set cm.Connection as cn
cm.Connection =cn;
OR
using (var cn = new SqlCeConnection("connection string"))
using (var cmd = new SqlCeCommand("insert addNew (no,session,name) values (#no,#session,#name)", cn))
{
cmd.Parameters.AddWithValue("#no", admNo.Text);
cmd.Parameters.AddWithValue("#session", session.Text);
cmd.Parameters.AddWithValue("#name", name.Text);
cn.Open();
cmd.ExecuteNonQuery();
}
This will help you to write the correct connection string for SQL CE
You have four mistakes:
You never associate the connection with the command
You're connecting to a Sql Server Compact database using the full Sql Server provider (you should be using the SqlCe namespace:
You're building your query using unsafe string concatenation instead of query parameters. Fix this!
Your connection won't be closed if an exception is thrown, which can ultimately lock you out of your database. You need to close the connection as part of a finally block, and the easiest way to do this is with a using block.
.
using (var cn = new SqlCeConnection("connection string here"))
using (var cmd = new SqlCeCommand("insert into addNew (no,session,name) values (#no,#session,#name)", cn))
{
//guessing at column lengths:
cmd.Parameters.Add("#no", SqlDbType.Int).Value = int.Parse(admNo.Text);
cmd.Parameters.Add("#session", SqlDbType.NVarChar, 100).Value = session.Text;
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 60).Value = name.Text;
cn.Open();
cmd.ExecuteNonQuery();
}
I can't make out what is the mistake. I wanted to retrieve a record from the database table and give them out. There are 9 fields in my table. The data of the second field is the search word. There can be more than one record for the same data. If there are many, then it must show each record at a time. How is it possible to code it?
I use C#.Net for logic and Ms Access for the back end(Database)
This is my code:
string[] arr = new string[9];
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="C:\PassWordSaver\Passwords.mdb;Persist Security Info=True;");
con.Open();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM pwd Where Title = '"+textBox2+"'", con);
OleDbDataReader reader = cmd.ExecuteReader();
reader.Read();
//while (reader.Read())
//{
for (int i = 0; i < 9; i++)
{
arr[i] = reader.GetValue(i).ToString();
MessageBox.Show("The New data is " + arr[i] + ".", "Created", MessageBoxButtons.OK);
}
//}
reader.Close();
MessageBox.Show("Data Added Successfully. " + arr[2] + " is the user name.", "Created", MessageBoxButtons.OK);
OleDbCommand cmd = new OleDbCommand("SELECT * FROM pwd Where Title = '"+textBox2+"'", con);
Should read:
OleDbCommand cmd = new OleDbCommand("SELECT * FROM pwd Where Title = '"+textBox2.Text+"'", con);
The reason you aren't entering your while loop is that the condition isn't being met to begin with. There is nothing for myReader to read. However, I don't understand why you don't get an error when you run that telling you that you can't convert a textbox control to a string.
First of all you're getting into the loop because your query doesn't return any results, and second of all you might want to try and put some parameters on this query like so:
OleDbCommand cmd = new OleDbCommand("SELECT * FROM pwd Where Title = ?", con);
cmd.Parameters.Add(textBox2.Text); // I assume you mean textBox2.Text
May be it will be a silly answer but I think you are trying to send query by taking the value from textbox.Text property. But on the code you are trying to get directly Textbox
OleDbCommand cmd = new OleDbCommand("SELECT * FROM pwd Where Title = '"+textBox2+"'", con);
I think you can update as follows
OleDbCommand cmd = new OleDbCommand("SELECT * FROM pwd Where Title = '"+textBox2.Text+"'", con);
i m trying to retrieve the Specialization ID from a table called Specializationtbl, using C# MSVS 2008 and the table includes SpecializationName and SpecializationID beside some other rows and my question is related to some error " No Data to present ", the command goes as bellow:
SqlCommand READSpecID = new SqlCommand("SELECT * FROM Specializationtbl WHERE SpecializationName='" + comboBox1.Text + "'" , DBcnction);
DBcnction.Open();
SqlDataReader ReadSpecID_ = READSpecID.ExecuteReader();
ReadSpecID_.Read();
int SpecID_ = Convert.ToInt16(ReadSpecID_["SpecID"].ToString());
DBcnction.Close();
i also tried to Select the "SpecID" instead of all the rows, but cant seem to seal the query correctly and keep receiving "No data present " error, any idea where am i making the mistake?
1) Try opening DBcnction before assigning the value to READSPecID
DBcnction.Open();
SqlCommand READSpecID = new SqlCommand("SELECT * FROM Specializationtbl WHERE SpecializationName='" + comboBox1.Text + "'" , DBcnction);
2) Run the command in SSMS:
SELECT * FROM Specializationtbl WHERE SpecializationName ='yourvalue'
and see if any results are returned
3) Check comboBox1.Text has a value in it
4) Validate the contents of comboBox1.Text (Or use paremetrised queries or a stored procedure) to ensure you do not become a victim of SQL Injection: http://en.wikipedia.org/wiki/SQL_injection
Refactor to solve your TWO problems:
Your SQL injection problem when building your SQL statement.
Use ExecuteScalar if you only need one value.
Implement using blocks.
string retVal;
using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT SpecID FROM Specializationtbl WHERE SpecializationName= #Name";
cmd.Parameters.AddWithValue("#Name", comboBox1.Text);
conn.Open();
retVal = cmd.ExecuteScalar().ToString();
}
int specID = int.Parse(retVal);
If you really needed more than one value from your statement:
using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT SpecID, Value2 FROM Specializationtbl WHERE SpecializationName= #Name";
cmd.Parameters.AddWithValue("#Name", comboBox1.Text);
conn.Open();
var dr = cmd.ExecuteReader();
while (dr.Read())
{
Customer c = new Customer {
ID = dr["SpecID"].ToString(),
Value = dr["Value2"].ToString(),
};
}
}
Need to first test if there are any rows. I suspect the query is returning zero rows.
if (ReadSpecID_.HasRows)
{
ReadSpecID_.Read();
}