Error in Syntax of FROM clause - c#

Here is my code that I thought worked but it continues to give me a syntax error in my FROM clause. Could someone help me understand what I am missing? Without the try\catch, it highlights the line int result = (int)cmd.ExecuteScalar();.
string constring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\jwhite\Documents\TrainingDB.accdb";
string cmdText = "SELECT COUNT(*) FROM USER WHERE Username=#p1 AND [Password]=#p2";
using (OleDbConnection con = new OleDbConnection(constring))
using (OleDbCommand cmd = new OleDbCommand(cmdText, con))
{
try
{
con.Open();
cmd.Parameters.AddWithValue("#p1", textBox1.Text);
cmd.Parameters.AddWithValue("#p2", textBox2.Text);
int result = (int)cmd.ExecuteScalar();
if (result > 0)
{
groupBox1.Visible = false;
groupBox2.Visible = true;
string commandText = "SELECT RIGHTS FROM USER WHERE Username=#p1 and [Password]=#p2";
using (OleDbCommand command = new OleDbCommand(commandText, con))
{
command.Parameters.AddWithValue("#p1", textBox1.Text);
command.Parameters.AddWithValue("#p2", textBox2.Text);
string query = (string)command.ExecuteScalar();
{
if (query == "Administrator")
{
toolStripMenuItem59.Enabled = true;
administratorToolStripMenuItem1.Enabled = true;
administratorToolStripMenuItem3.Enabled = true;
administratorToolStripMenuItem4.Enabled = true;
administratorToolStripMenuItem5.Enabled = true;
administratorToolStripMenuItem2.Enabled = true;
administratorToolStripMenuItem6.Enabled = true;
toolStripMenuItem92.Enabled = true;
toolStripMenuItem108.Enabled = true;
}
}
}
}
else
MessageBox.Show("Invalid Credentials, Please Try Again");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to " + ex.Message);
}
}

Instead of USER write [USER] as USER is a reserved word.
See List of Reserved Words HERE

According to http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand.parameters.aspx OleDbCommand does not support named parameter
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text. In this case, the
question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.
So order of parameter is important.

Related

.Rows.Count always returns -1 even if record in database already exists?

Basically I want to check, using c#, if there is a username in the database already existing. If there is not-it must be created.
Below is the code that is doing exactly that(only the checking part matters in my opinion, but I have added the code for the adding part anyways)
Problem is that no matter what-if it exists or not, it always returns -1
public Boolean checkUser()
{
var connection = new MySqlConnection("Server=127.0.0.1;Database=book_library;user=root;password=root2");
var table = new DataTable();
connection.Open();
string checkUsernameQuery = "SELECT * FROM accounts WHERE username = 'usernameInputField.Text'";
var adapter = new MySqlDataAdapter();
MySqlCommand command = new MySqlCommand(checkUsernameQuery, connection);
//command.Parameters.Add("#username", MySqlDbType.VarChar).Value = usernameInputField.Text;
adapter.SelectCommand = command;
adapter.Fill(table);
if (table.Rows.Count > 0)
{
return true;
}
else
{
return false;
}
}
Here is the adding part(just adding it, but it is not too related with the problem)
private void registerIconButton_Click(object sender, EventArgs e)
{
checkUser();
var connection = new MySqlConnection("Server=127.0.0.1;Database=book_library;user=root;password=root2");
connection.Open();
string insertQuery = "INSERT INTO `accounts` (username, password, email) VALUES ('" + usernameInputField.Text + "','" + passwordInputField.Text + "','" + emailInputField.Text + "')";
MySqlCommand command = new MySqlCommand(insertQuery, connection);
command.Parameters.Add("#username", MySqlDbType.VarChar).Value = usernameInputField.Text;
command.Parameters.Add("#password", MySqlDbType.VarChar).Value = passwordInputField.Text;
command.Parameters.Add("#email", MySqlDbType.VarChar).Value = emailInputField.Text;
if (checkUser())
{
MessageBox.Show("This username already exists!");
}
else
{
if (command.ExecuteNonQuery() == 1)
{
}
else
{
MessageBox.Show("ERROR");
}
}
connection.Close();
}
Connections and Commands are disposable so you should put them inside using blocks to deterministically clean up resources.
If you just want to know if something exists, you can use ExecuteScalar instead of using a heavy-weight adapter.
Then just return the result of the expression != null to get your boolean that indicates if the user is there or not.
using(var connection = new MySqlConnection("Server=127.0.0.1;Database=book_library;user=root;password=root2"))
using(var cmd = connection.CreateCommand())
{
connection.Open();
string checkUsernameQuery = "SELECT TOP 1 username FROM accounts WHERE username = #p1";
cmd.Parameters.Add(new MySqlParameter("#p1", MySqlDbType.VarChar).Value = usernameInputField.Text;
var user = cmd.ExecuteScalar();
return user != null;
}

Retrieving ID while having only user_name

I'm trying to make a private message system.
What I have so far.
- checking if player exists with the name from textbox, if not, error shows up.
Now, I'm trying to insert it to the table. The problem is that the table have 2 colums
to_user_id
from_user_id
And becasuse I'm using a textbox to enter the name of the user, I dont how to retrieve to_user_id from users table while having only name.
this is my code
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ToString());
conn.Open();
SqlCommand cmdd = new SqlCommand();
cmdd.CommandText = "select * from [users]";
cmdd.Connection = conn;
SqlDataReader rd = cmdd.ExecuteReader();
while (rd.Read())
{
if (rd[1].ToString() == TextBox_To.Text)
{
flag = false;
break;
}
}
conn.Close();
if (flag == true)
{
Label1.Visible = true;
Label1.Text = "User does not exist";
}
else if(flag == false)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ToString()))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = #"INSERT INTO messages (message_title, message_content, to_user_id, from_user_id, message_date)
VALUES (#title, #content, #to, #from, #date)";
cmd.Parameters.AddWithValue("#title", TextBox_Title.Text);
cmd.Parameters.AddWithValue("#content", TextBox_Msg.Text.Replace("\n", "<br/>"));
cmd.Parameters.AddWithValue("#to", TextBox_To.Text);
cmd.Parameters.AddWithValue("#date", DateTime.Now);
cmd.Parameters.AddWithValue("#from", Session["id"].ToString());
con.Open();
cmd.ExecuteNonQuery();
}
}
Of course I got an error
Conversion failed when converting the nvarchar value 'username' to data type int.
#edit,
#cordan I tried this
DECLARE #user_id = (SELECT id FROM users WHERE user_login=#to );
INSERT INTO messages (message_title, message_content, to_user_id, from_user_id, message_date)
VALUES (#title, #content, #user_id, #from, #date);
cmd.Parameters.AddWithValue("#to", TextBox_To.Text);
got this error
Incorrect syntax near '='.
Must declare the scalar variable "#user_id".
This bit here is a huge NO!!
SqlCommand cmdd = new SqlCommand();
cmdd.CommandText = "select * from [users]";
cmdd.Connection = conn;
SqlDataReader rd = cmdd.ExecuteReader();
while (rd.Read())
{
if (rd[1].ToString() == TextBox_To.Text)
{
flag = false;
break;
}
}
conn.Close();
You are selecting every single user from the users table, just to determine if the one you're trying to find exists.
Aside from the fact that you could almost certainly just add:
if (rd[1].ToString() == TextBox_To.Text)
{
foundUserId = (int)rd[0]; // I'm assuming the first column in users is the Id - it probably is
flag = false;
break;
}
DONT DO THAT!!
Instead, you should just be looking for the one username you're interested in
SqlCommand cmdd = new SqlCommand();
cmdd.CommandText = "select top 1 Id from [users] where username=#username";
cmdd.Parameters.AddWithValue("#username",username);
cmdd.Connection = conn;
SqlDataReader rd = cmdd.ExecuteReader();
var userId = 0;
if(rd.Read())
{
userId = (int)rd[0];
}
conn.Close();
if (userId == 0)
{
Label1.Visible = true;
Label1.Text = "User does not exist";
return;
}
else
.... // userId holds the users Id
...
cmd.Parameters.AddWithValue("#to", userId);

How to Query Return Value on using Compact SQL Command?

I using a compact database created on visual studio. just for a stand alone system with it's database intact already although i'm stuck here in using a select query that could retrieve a boolean if the user exist on the database and also then return it's ID and Username if the user entry exist. can i ask for help regarding on this one.. I am a student trying to learn c# on using compact database.
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
if (!IsEmpty())
{
if (!IsLenght())
{
using (SqlCeConnection con = new SqlCeConnection("Data Source=" +
System.IO.Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "INCdb.sdf")))
{
con.Open();
SqlCeCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT * FROM LoginTB Where username=#user1 AND password=#pass1";
cmd.Parameters.AddWithValue("#user1", UserTxt.Text.Trim());
cmd.Parameters.AddWithValue("#pass1", PassTxt.Text.Trim());
cmd.CommandType = CommandType.Text;
validlogin = (bool)cmd.ExecuteScalar();
con.Close();
MessageBox.Show(validlogin.ToString());
if (validlogin == true)
{
// cmd. return value ID
// cmd. return value Username
//SysMain Mn = new SysMain();
//Mn.ShowDialog();
//this.Hide();
}
}
}
}
}
catch (Exception ex)
{
gbf.msgBox(1, ex.Message.ToString(), "");
}
}
The code below is probably better, unless there is something special and unstated about the schema of LoginTB.
// ...
var validLogin = false;
using (SqlCeConnection con = new SqlCeConnection(
"Data Source=" +
System.IO.Path.Combine(
Path.GetDirectoryName(
System.Reflection.Assembly.GetEntryAssembly().Location),
"INCdb.sdf")))
{
con.Open();
SqlCeCommand cmd = con.CreateCommand();
cmd.CommandText =
"SELECT COUNT(*) FROM LoginTB Where username=#user1 AND password=#pass1";
cmd.Parameters.AddWithValue("#user1", UserTxt.Text.Trim());
cmd.Parameters.AddWithValue("#pass1", PassTxt.Text.Trim());
cmd.CommandType = CommandType.Text;
validlogin = ((int)cmd.ExecuteScalar()) > 0;
}
MessageBox.Show(validlogin.ToString());
// ...
Note the use of COUNT

ASP.Net C# - Setting a MySQL query and parameters based on a condition

How do I go about setting a MySQL query and parameters based on a condition?
I want different queries based on 'questionSource' as shown below.
However, in my code below, 'cmd' does not exist in the current context.
Alternatively, I could have two different functions for each condition and call the necessary function as required but I imagine there must be a way to have conditions within a connection.
//validation checks
else
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
string questionSource = Session["QuestionSource"].ToString();
string cmdText = "";
if (questionSource.Equals("S"))
{
cmdText += #"SELECT COUNT(*) FROM questions Q
JOIN users U
ON Q.author_id=U.user_id
WHERE approved='Y'
AND role=1
AND module_id=#ModuleID";
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
}
else if (questionSource.Equals("U"))
{
cmdText += "SELECT COUNT(*) FROM questions WHERE approved='Y' AND module_id=#ModuleID AND author_id=#AuthorID;";
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
cmd.Parameters.Add("#AuthorID", MySqlDbType.Int32);
cmd.Parameters["#AuthorID"].Value = Convert.ToInt32(Session["UserID"]);
}
int noOfQuestionsAvailable = 0;
int noOfQuestionsWanted = Convert.ToInt32(ddlNoOfQuestions.SelectedValue);
try
{
conn.Open();
noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());
if (noOfQuestionsAvailable < noOfQuestionsWanted)
{
lblError.Text = "There are not enough questions available to create a test.";
}
else
{
Session["TestName"] = txtName.Text;
Session["NoOfQuestions"] = ddlNoOfQuestions.SelectedValue;
Session["QuestionSource"] = rblQuestionSource.SelectedValue;
Session["TestModuleID"] = ddlModules.SelectedValue;
Response.Redirect("~/create_test_b.aspx");
}
}
catch
{
lblError.Text = "Database connection error - failed to get module details.";
}
finally
{
conn.Close();
}
}
declare cmd before if
MySqlCommand cmd = new MySqlCommand("",connStr);
and in each part of if
cmd.CommandText=cmdText;
other suggestion: add
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
always before if because it is used in the same way in if and else part
You just have to move the declaration of the cmd outside the if block:
//validation checks
else
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
string questionSource = Session["QuestionSource"].ToString();
string cmdText = "";
MySqlCommand cmd; // <-- here
if (questionSource.Equals("S"))
{
cmdText += #"SELECT COUNT(*) FROM questions Q
JOIN users U
ON Q.author_id=U.user_id
WHERE approved='Y'
AND role=1
AND module_id=#ModuleID";
cmd = new MySqlCommand(cmdText, conn); // remove MySqlCommand here
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
}
else if (questionSource.Equals("U"))
{
cmdText += "SELECT COUNT(*) FROM questions WHERE approved='Y' AND module_id=#ModuleID AND author_id=#AuthorID;";
cmd = new MySqlCommand(cmdText, conn); // remove MySqlCommand here
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
cmd.Parameters.Add("#AuthorID", MySqlDbType.Int32);
cmd.Parameters["#AuthorID"].Value = Convert.ToInt32(Session["UserID"]);
}
int noOfQuestionsAvailable = 0;
int noOfQuestionsWanted = Convert.ToInt32(ddlNoOfQuestions.SelectedValue);
try
{
conn.Open();
noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());
if (noOfQuestionsAvailable < noOfQuestionsWanted)
{
lblError.Text = "There are not enough questions available to create a test.";
}
else
{
Session["TestName"] = txtName.Text;
Session["NoOfQuestions"] = ddlNoOfQuestions.SelectedValue;
Session["QuestionSource"] = rblQuestionSource.SelectedValue;
Session["TestModuleID"] = ddlModules.SelectedValue;
Response.Redirect("~/create_test_b.aspx");
}
}
catch
{
lblError.Text = "Database connection error - failed to get module details.";
}
finally
{
conn.Close();
}
}
Just move the declaration of the MySqlCommand outside the if/else blocks so you could use it in the final try where you execute the command
//validation checks
else
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using(MySqlConnection conn = new MySqlConnection(connStr))
using(MySqlCommand cmd = conn.CreateCommand())
{
// Don't need to associate the command to the connection
// Already done by the CreateCommand above, just need to set
// the parameters and the command text
if (questionSource.Equals("S"))
{
cmdText = #"....."
cmd.CommandText = cmdText;
....
}
else if (questionSource.Equals("U"))
{
cmdText = "........."
cmd.CommandText = cmdText;
....
}
try
{
conn.Open();
noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());
....
}
}
}
Notice also that you should use the using statement to be sure that your connection and your command are propertly closed and disposed.

Error: The type 'System.Data.OleDb.OleDbDataReader' has no constructors defined

I am trying to change password option with ms access database....
please help me folks....
here the code:
default.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
try
{
OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["vhgroupconnection"].ConnectionString);
myCon.Open();
string userid = txtuserid.Text;
string oldpass = txtoldpass.Text;
string newPass = txtnewpass.Text;
string conPass = txtconfirmpass.Text;
string q = "select user_id,passwd from register where user_id = #userid and passwd = #oldpass";
OleDbCommand cmd = new OleDbCommand(q, myCon);
OleDbDataReader reader = new OleDbDataReader();
cmd.Parameters.AddWithValue("#userid", txtuserid.Text);
cmd.Parameters.AddWithValue("#oldpass", txtoldpass.Text);
reader = cmd.ExecuteReader();
reader.Read();
if (reader["user_id"].ToString() != String.Empty && reader["passwd"].ToString() != String.Empty)
{
if (newPass.Trim() != conPass.Trim())
{
lblmsg.Text = "New Password and old password does not match";
}
else
{
q = "UPDATE register SET passwd = #newPass WHERE user_id =#userid";
cmd = new OleDbCommand(q, myCon);
cmd.Parameters.AddWithValue("#newPasss", txtnewpass.Text);
cmd.Parameters.AddWithValue("#userod", txtuserid.Text);
cmd.Parameters.AddWithValue("#passwd", txtoldpass.Text);
int count = cmd.ExecuteNonQuery();
if (count > 0)
{
lblmsg.Text = "Password changed successfully";
}
else
{
lblmsg.Text = "password not changed";
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
also check pls.....
Compilation Error Description: An error occurred during the
compilation of a resource required to service this request. Please
review the following specific error details and modify your source
code appropriately.
Compiler Error Message: CS0143: The type
'System.Data.OleDb.OleDbDataReader' has no constructors defined
Source Error:
Line 36: OleDbCommand cmd = new OleDbCommand(q, myCon);
Line 37:
Line 38: OleDbDataReader reader = new OleDbDataReader();
Line 39:
Line 40:
As error message says; OleDbDataReader has no constructor.
From documentation of OleDbDataReader;
To create an OleDbDataReader, you must call the ExecuteReader method
of the OleDbCommand object, instead of directly using a constructor.
You can use ExecuteReader method that returns OleDbDataReader
OleDbDataReader dr = cmd.ExecuteReader();
And you need add your parameter values before you call ExecuteReader method.
Also use using statement to dispose your OleDbConnection, OleDbCommand and OleDbDataReader like;
using(OleDbConnection myCon = new OleDbConnection(conString))
using(OleDbCommand cmd = myCon.CreateCommand())
{
//Define your sql query and add your parameter values.
using(OleDbDataReader dr = cmd.ExecuteReader())
{
//
}
}
And as Steve mentioned, OleDbDataReader.Read method returns boolean value (true of false) and it reads your OleDbDataReader results row by row. You might need to consider to use the result of this method like in a while statement. For example;
while(reader.Read())
{
//Reads your results until the last row..
}
As a final words, I strongly suspect you store your passwords as plain text. Don't do that! Use SHA-512 hash.
As MSDN clearly states, To create an OleDbDataReader, you must call the ExecuteReader method of the OleDbCommand object, instead of directly using a constructor.
You cannot instantiate it using new, which is what you are doing and which is why you get the error. Remove the offending line and change it to this to get rid of the error:
OleDbDataReader reader = cmd.ExecuteReader();
Also, remember to use using blocks to ensure resources get properly disposed.
using(OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["vhgroupconnection"].ConnectionString))
{
OleDbCommand cmd = new OleDbCommand(q, myCon);
//Add parameters etc
OleDbDataReader reader = cmd.ExecuteReader();
//Rest of the processing
}
Problem: You try to make new instance of OleDbDataReader by calling new OleDbDataReader() instead you should create a reader using OleDbCommand.ExecuteReader().
In the following code notice use of using statement (this should ensure connection closing or reader closing for the case of OleDbDataReader).
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string sConnString = ConfigurationManager.ConnectionStrings["vhgroupconnection"].ConnectionString;
using(OleDbConnection myCon = new OleDbConnection(sConnString))
{
myCon.Open();
string userid = txtuserid.Text;
string oldpass = txtoldpass.Text;
string newPass = txtnewpass.Text;
string conPass = txtconfirmpass.Text;
string q = "select user_id,passwd from register where user_id = #userid and passwd = #oldpass";
OleDbCommand cmd = new OleDbCommand(q, myCon);
cmd.Parameters.AddWithValue("#userid", txtuserid.Text);
cmd.Parameters.AddWithValue("#oldpass", txtoldpass.Text);
string sUserId = string.Empty;
string sPass = string.Empty;
using(OleDbDataReader reader = cmd.ExecuteReader())
{
if(reader.Read()) //assumption: one record returned
{
sUserId = reader["user_id"].ToString();
sPass = reader["passwd"].ToString();
}
}
if (sUserId != string.Empty && sPass != string.Empty)
{
if (newPass.Trim() != conPass.Trim())
lblmsg.Text = "New Password and old password does not match";
else
{
q = "UPDATE register SET passwd = #newPass WHERE user_id =#userid";
cmd = new OleDbCommand(q, myCon);
cmd.Parameters.AddWithValue("#newPass", txtnewpass.Text);
cmd.Parameters.AddWithValue("#userid", txtuserid.Text);
int count = cmd.ExecuteNonQuery();
if (count > 0)
lblmsg.Text = "Password changed successfully";
else
lblmsg.Text = "password not changed";
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}

Categories

Resources