I'm trying to login to my application from my microsoft access database I'm making right now but I'm getting this error "Syntax error (comma) in query expression ('StudentID', 'Password')." Can anyone give me a fix please?
This is the code where the error is coming from:
con.Open();
string login = "SELECT (StudentID, Password) FROM Student WHERE StudentID = '"+txtStudentID+ "' and Password = '" + txtPassword + "'";
cmd = new OleDbCommand(login, con);
OleDbDataReader dr = cmd.ExecuteReader();
Take off the parentheses:
SELECT StudentID, Password FROM Student ...
And while using parameters to prevent SQL injection is very important (even if this is a school or learning project, as bad habits are hard to break), it is not the source of the problem.
You should remove the parentheses first, also using string interpolation is much better and more readable!
con.Open();
string login = $"SELECT StudentID, Password FROM Student WHERE StudentID = '{txtStudentID.text}' and Password = '{txtPassword.text}' ";
cmd = new OleDbCommand(login, con);
OleDbDataReader dr = cmd.ExecuteReader();
But the complete solution is the below and for avoiding SQL Injection you should use SQL parameters :
SqlParameter userName = new SqlParameter()
{
ParameterName = "#UserName",
DbType = DbType.String,
Direction = ParameterDirection.Input,
Value = txtStudentID.text
};
SqlParameter password = new SqlParameter()
{
ParameterName = "#Password",
DbType = DbType.String,
Direction = ParameterDirection.Input,
Value = txtPassword.text
};
SqlCommand command = new SqlCommand
{
Connection = connection,
CommandType = CommandType.Text,
CommandText = $"SELECT * FROM Student WHERE StudentID = #UserName and Password = #Password"
};
command.Parameters.Add(userName);
command.Parameters.Add(password);
con.Open();
....
Related
When i use the CustomButton for to save the "Full_Name" in the Database [Rooms] => Person then there is just nothing happen. Also if i use the try & catch function, there will be no Exception.
The field in the Database stays Empty.
When i show the required variable in the MessageBox (idPlus2, Full_Name) then it throws me back the right informations.
So i think the problem must be in the UPDATE Sql string but i don't know whats wrong.
private string connstr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\....mdb";
//Path anonymous
string Full_Name;
[Obsolete]
private void customButton1_Click(object sender, EventArgs e)
{
conn = new OleDbConnection(connstr);
conn.Open();
strSQL = "SELECT * FROM [Guests] WHERE ID = ?";
cmd = new OleDbCommand(strSQL, conn);
da = new OleDbDataAdapter(cmd);
int id = CustomComboBox1.SelectedIndex;
int idPlus = id + 1;
cmd.Parameters.Add("?", idPlus);
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Full_Name = reader["Vorname"].ToString() + ' ' + reader["Nachname"].ToString();
}
reader.Close();
string insertQuery = #"UPDATE [Rooms] SET Person = #Full_Name WHERE ID = ?";
cmd = new OleDbCommand(insertQuery, conn);
int id2 = customComboBox2.SelectedIndex;
int idPlus2 = id2 + 2;
cmd.Parameters.Add("?", idPlus2);
cmd.Parameters.Add(new OleDbParameter("#Full_Name", Full_Name));
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
conn.Close();
LoadTheme();
}
I have the answer
cmd.Parameters.Add("?", OleDbType.VarChar, 255).Value = CustomComboBox1.Texts;
cmd.Parameters.Add("?", idPlus2);
With OleDb you have to use ? for each variable or object which should be added to the database. That means that you can't specify the variable by name in the SQL string. You have to use the same order as the SQL string in C # code to insert the parameters.
Im using Database Data for my Project and when I type a letter in Textbox1, the application crashes with the error:
System.Data.SqlClient.SqlException: "Invalid column name 'e'."
Database name is Table with "Id" and "altitudes"
Id is a varchar and altitudes is a nchar.
Thats how I want it to work:
Typing a Name in name.Text, search for the name in the database and paste the assigned altitude in altitude.Text.
Altitudes are numbers, Names are Letters in the database.
Where's the error in my code? (Data Source is on purpose blank)
{
String source = #"Data Source=";
SqlConnection con = new SqlConnection(source);
con.Open();
String sqlSelectQuery = "SELECT * FROM [Table] WHERE ID ="+char.Parse(name.Text);
SqlCommand cmd = new SqlCommand(sqlSelectQuery, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
altitude.Text = (dr["altitudes"].ToString());
}
con.Close();
}
You should never concatenate inputs to create SQL. It is horribly brittle, and susceptible to SQL injection, and i18n/l10n problems (formatting of values). Lots of bad things.
The solution should always be: parameters.
For example:
const string sqlSelectQuery = "SELECT * FROM [Table] WHERE ID = #id";
using SqlCommand cmd = new SqlCommand(sqlSelectQuery, con);
cmd.Parameters.AddWithValue("#id", name.Text);
// Etc
Or more easily with a tool like Dapper:
var alt = con.QuerySingleOrDefault<string>(
"SELECT altitudes FROM [Table] WHERE ID = #id",
new { id = name.Text });
Assign entered texbox value to Sql query |C#|Oracle
How do i assign the Textbox value to my SQL Query C#
In the Above Image i typed Tablename = PERSONDETAILS this entered value in textBox1.Text should be passed to my SQL Query as a Paramter.So Hard coding the table name in the SQl query will be reduced
Actual code where i want it to be Included
select dbms_metadata.get_ddl('TABLE',table_name,user) AS my_ddl from all_tables where owner ='HR' AND table_name ='PERSONDETAILS'"
code :
OracleConnection con = new OracleConnection();
con.ConnectionString = conString;
con.Open();
OracleCommand cmd = con.CreateCommand();
cmd.Parameters.Add("userid", OracleDbType.Varchar2, 20).Value = textBox1.Text.ToString();
cmd.Parameters.Add("tableName", OracleDbType.Varchar2, 20).Value = texttablename.Text.ToString();
//cmd.CommandText = "select * from all_all_tables WHERE table_name=:tableName";
cmd.CommandText ="select dbms_metadata.get_ddl('TABLE',table_name,user) AS my_ddl from all_tables where owner = :userid AND table_name = :tableName";
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
textBox6.Text = reader.GetString(0);
}
con.Close();
You need to pass value of a textbox as a parameter to your command through Parameters property of OracleCommand.
So all you need to include in your code is:
cmd.CommandText = "select * from all_all_tables WHERE table_name=:tableName";
cmd.Parameters.Add("tableName", OracleType.VarChar, 20).Value = textBox1.Text;
Update regarding comments:
cmd.CommandText ="select dbms_metadata.get_ddl('TABLE',table_name,user) AS my_ddl from all_tables where owner = :userid AND table_name = :tableName";
// here you might want to use appropiate datatype
cmd.Parameters.Add("userid", OracleDbType.Varchar2, 20).Value = textBox1.Text;
cmd.Parameters.Add("tableName", OracleDbType.Varchar2, 20).Value = texttablename.Text;
I have a code that should test a login.
When I execute literally, it works, returning one row (that's expected). When I use parameters on sqlcommand, I don't get any row.
It works (literal values for username and password):
string strConn = 'string connection';
SqlConnection conn = new SqlConnection(strConn);
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = conn;
sqlCommand.Parameters.Clear();
sqlCommand.CommandText = #"select *
from
Usuario
where
Username = 'test' and
Password = CONVERT(VARCHAR(32), ashBytes('MD5', 'test'), 2)";
conn.Open();
SqlDataReader ret = sqlCommand.ExecuteReader();
But it doesn't work (parameters values for username and password):
string strConn = 'string connection';
SqlConnection conn = new SqlConnection(strConn);
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = conn;
sqlCommand.Parameters.Clear();
sqlCommand.CommandText = #"select *
from
Usuario
where
Username = #login and
Password = CONVERT(VARCHAR(32), ashBytes('MD5', #pass), 2)";
SqlParameter user = new SqlParameter("#login", SqlDbType.NVarChar, 50) { Value = "test" };
SqlParameter pass = new SqlParameter("#pass", SqlDbType.NVarChar, 50) { Value = "test" };
List<SqlParameter> list = new List<SqlParameter>();
list.Add(user);
list.Add(pass);
sqlCommand.Parameters.AddRange(list.ToArray<SqlParameter>());
conn.Open();
SqlDataReader ret = sqlCommand.ExecuteReader();
I don't have an sintax error or something like that. The second code just don't returns rows.
I've tried to use sqlCommand.Parameters.AddWithValue, but I have no success too.
'test' and N'test' are not the same thing when you convert them to a hash. One is ASCII and the other is Unicode. If they are both ASCII then use SqlDbType.VarChar (not SqlDbType.NVarChar) in your parameter.
Difference illustrated in Sql
DECLARE #passUnicode Nvarchar(100) = N'test'
DECLARE #passAscii varchar(100) = 'test'
SELECT CONVERT(VARCHAR(32), HashBytes('MD5', #passAscii), 2) AS [Md5OfAscii]
, CONVERT(VARCHAR(32), HashBytes('MD5', #passUnicode), 2) AS [Md5OfUnicode]
Results
098F6BCD4621D373CADE4E832627B4F6, C8059E2EC7419F590E79D7F1B774BFE6
Side notes
Password Hashing
I recommend against storing passwords as MD5, MD5 is simply not secure. There are plenty of alternatives out there like pbkdf2, bcrypt, and scrypt to name a few of the more generally accepted secure password hashing algorithms.
c# structure
When working with Ado.net (or with any resources for that matter) you should wrap your Connections, DataReaders, Adapters, etc that implement IDisposable in using blocks. This will ensure external resources are always freed, even in the event of a connection.
string connectionString = "";
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand
{
CommandText = #"select * from Usuario where Username = #login and Password = CONVERT(VARCHAR(32), HASHBYTES('MD5', #pass), 2)",
CommandType = CommandType.Text,
Connection = connection
})
{
command.Parameters.Add(new SqlParameter("login", SqlDbType.VarChar, 50) { Value = "test" });
command.Parameters.Add(new SqlParameter("pass", SqlDbType.VarChar, 50) { Value = "test" });
connection.Open();
using (var dataReader = command.ExecuteReader())
{
// do some stuff
}
}
}
I am just starting work with ASP.NET C# and my database is SQL Server. I am trying to write a query where I want to use with prepared statement.
This is a query that allowing log in to user:
SqlParameter UserName = new SqlParameter("#user", SqlDbType.NVarChar, 30);
SqlParameter Password = new SqlParameter("#pass", SqlDbType.NVarChar, 20);
UserName.Value = user.ToLower();
Password.Value = pass;
SqlCommand command = new SqlCommand(null, conn);
command.Parameters.Add(UserName);
command.Parameters.Add(Password);
command.CommandText = "SELECT * FROM table_users WHERE user_name = '#user' AND password = '#pass';";
command.Prepare();
SqlDataReader reader = command.ExecuteReader();
bool tmp = reader.HasRows;
tmp variable value always FALSE, even when I enter exist user with correct password.
If i just remove parameters and write the query this way:
command.CommandText = "SELECT * FROM table_users WHERE user_name = '"+user+"' AND password = '"+ pass+"';";
tmp variable get value TRUE for exists users.
I tried to use this syntax for INSERT INTO queries and it works correctly.
I already read all the suggestions about changing # to ? and it doesn't work.
I had an error:
Incorrect syntax near '?'. Statement(s) could not be prepared.
Help me please,
Thanks!
You are looking for the literals '#user' and '#pass', rather than the value from the parameter; use:
command.CommandText =
"SELECT * FROM table_users WHERE user_name = #user AND password = #pass;";
instead. Then look into "salted hashes", and why you should never actually store passwords.
BTW, calling Prepare() here isn't helping here. I'm also going to plug dapper-dot-net (free/OSS), which would make this entire thing just:
bool authenticated = conn.Query(
#"select 1 from table_users where user_name = #user and password = #pass",
new {user = user.ToLower(), pass} ).Any();
or, if you want the record:
var tableUser = conn.Query<TableUser>(
#"select * from table_users where user_name = #user and password = #pass",
new {user = user.ToLower(), pass} ).SingleOrDefault();