I have SQL Server Compact 3.5 database that contains account information. But everytime I call the function ExecuteReader I get this exception below:
The column name is not valid. [ Node
name (if any) = ,Column name = ID ]
But that is the correct column name. The column names are the following: Username, Password, Date Created, and etc.
Here is the code below:
SqlCeConnection connection = new SqlCeConnection(#"Data Source=C:\Users\Danny\Documents\Visual Studio 2010\Projects\Databinding Login Form\Databinding Login Form\MyDatabase#1.sdf; Password=*********");
connection.Open();
SqlCeCommand com = new SqlCeCommand("SELECT * FROM Accounts WHERE ID=Username", connection);
SqlCeDataReader reader = com.ExecuteReader();
if (username.Text == reader["Username"] as string && password.Text == reader["Password"] as string)
{
MessageBox.Show("Login Successfull!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Access Denied 5", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Do you have a column called "ID"?
It looks like you are asking for all accounts which have the same value in "Username" and "ID" columns? Did you meant to substitute "ID" for something?
Example
Where Username = 'EnteredUsername'
Looks like your query "SELECT * FROM Accounts WHERE ID=Username" may be the problem. As you mentioned Username is a column-name; looks like you should be putting the user id in the query i.e "dlopez" for instance: "SELECT * FROM Accounts WHERE ID='dlopez'"
The where clause is cause the error. I assume you want to select only one Account where the ID is equal to a local variable caller username. One solution is:
SqlCeCommand com = new SqlCeCommand("SELECT * FROM Accounts WHERE ID='"
+ username + "'", connection);
A more correct solution is to use a SqlCeParameter:
SqlCeCommand com = new SqlCeCommand("SELECT * FROM Accounts WHERE ID=#UserName", connection);
SqlCeParameter param = new SqlCeParameter("#UserName", SqlDbType.NVarChar);
param.Value = username;
com.Parameters.Add(param);
Related
I'm writing an application which stores user information. Currently the user is supposed to update their Name, Height, Weight and Birthday.
string height = TB_ClientHeight.Text;
string weight = TB_ClientWeight.Text;
string name = TB_ClientName.Text;
string bday = dateTimePicker1.Value.ToString("dd-MM-yyyy");
int heightint = Convert.ToInt32(height);
int weightint = Convert.ToInt32(weight);
It's updated by calling the public static string username variable from another form and using that as the WHERE UserName = #username.
usernamestringo = Login.usernameFromLogin;
I've followed other SO answers in this context and corrected some issues (like preventing SQL Injection). However I'm still getting a syntax error while updating these fields as claimed by OleDbException.
using (OleDbConnection myCon = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=O:\Repos\Database\Database.accdb;Persist Security Info=False"))
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.CommandType = CommandType.Text;
string query = "UPDATE TPersons SET Name=#Name, SET Height=#Height, SET Weight=#Weight, SET Bday=#Bday " + " WHERE FirstName= #username";
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#Name", name.ToString());
cmd.Parameters.AddWithValue("#Height", heightint.ToString());
cmd.Parameters.AddWithValue("#Weight", weightint.ToString());
cmd.Parameters.AddWithValue("#Bday", bday.ToString());
cmd.Parameters.AddWithValue("#username", usernamestringo);
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Updated!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
cmd.Parameters.Clear();
}
The OleDbException is:
Index #0
NativeError: -526847407
Source: Microsoft Access Database Engine
SQLState: 3000
Description (message): Syntax error in UPDATE statement.
Could anyone guide me where my syntax is wrong? Thank you!
The UPDATE syntax is
UPDATE <tablename> SET field1=Value1, field2=Value2 WHERE primarykeyname=Value3
The SET keyword precedes only the first column to update, and you have another problem with the NAME column. In Access this is a reserved keyword. Use brackets around that column name (or better change it to something not so troublesome)
So:
string query = #"UPDATE TPersons SET [Name]=#Name,
Height=#Height, Weight=#Weight, Bday=#Bday
WHERE FirstName= #username";
Not strictly related to your current problem, but you should look also at this article Can we stop using AddWithValue already? The DbCommand.AddWithValue is a shortcut with numerous drawbacks. Better avoid it.
I have two text boxes in my winform. I would like to enter a userId into first text box, after that by clicking a button display a User Name in the second text box properly. The data is stored in sql server compact. Table name is Users, and this table contains two columns UserID and UserName.
With this code I can open a connection and retrieve the first value from the UserName column,
SqlCeConnection cn = new SqlCeConnection(#"Data Source = D:\Database\Training.sdf");
try
{
cn.Open();
SqlCeCommand cmd = new SqlCeCommand("SELECT UserID, UserName from Users;", cn);
TrainerNameBox.Text = cmd.ExecuteScalar().ToString();
cn.Close();
}
catch
{
}
ExecuteScalar returns first column of the first row. Other columns or rows are ignored.
In your case, your first column is UserID. That's why you get first value of this column.
If you want to get UserName value, you might need to change your query like;
SELECT UserName from Users
And looks like you forget to use WHERE clause in your query since you want to get UserName from UserID. You might need to use using statement to dispose your SqlCeConnection and SqlCeCommand.
Full example;
using(SqlCeConnection cn = new SqlCeConnection(#"Data Source = D:\Database\Training.sdf"))
using(SqlCeCommand cmd = cn.CreateCommand())
{
cmd.CommandText = "SELECT UserName from Users WHERE UserID = #id";
cmd.Parameters.AddWithValue("#id", (int)txtUserID.Text);
cn.Open();
TrainerNameBox.Text = cmd.ExecuteScalar().ToString();
}
You are missing the WHERE clause to isolate the username that you want to display
int userID;
if(!Int32.TryParse(txtUserID.Text, out userID))
{
MessageBox.Show("Invalid User ID number");
return;
}
using(SqlCeConnection cn = new SqlCeConnection(#"Data Source = D:\Database\Training.sdf"))
using(SqlCeCommand cmd = new SqlCeCommand("SELECT UserName from Users WHERE UserID=#id;", cn))
{
cn.Open();
cmd.Parameters.AddWithValue("#id", userID);
object result = cmd.ExecuteScalar();
if(result != null)
TrainerNameBox.Text = result.ToString();
else
MessageBox.Show("No user for ID=" + userID.ToString());
}
Notice that ExecuteScalar returns the first column of the first row, so you need to remove the UserID field from your query and if, the user is not found, you need to check for a null return.
Applying directly the ToString() method to your ExecuteScalar could raise an exception if your user types an invalid id. There is also the problem to validate the user input. If you type a not numeric value for the user id, the conversion will fail. In this case you need to check the input using Int32.TryParse
Try this:
Dataset ds = cmd.ExecuteDataset().ToString();
TrainerNameBox.Text = ds.tables[0].Rows[0][1].toString();
TrainerIDBox.Text = ds.tables[0].Rows[0][0].toString();
I made a login form for an application, and I want to check if the login data from the user exists in the database so that he can log in successfully or display an message telling him that his login details are wrong.
I tried the OleDbDataReader but that didn't work, so I added a username and password in my database (in the table Etudiant) and tried to count the number of rows in the table Etudiant, so that the login succeeds if the count is greater than 0, otherwise "wrong details" is shown. But the problem is always the same, only the second message is shown.
Here's my code:
string strcnn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=app.mdb";
OleDbConnection cnn = new OleDbConnection(strcnn);
cnn.Open();
string reqet = "SELECT count(*) FROM Etudiant";
OleDbCommand cmd = new OleDbCommand(reqet, cnn);
int x = (int)cmd.ExecuteScalar();
if (x>0)
MessageBox.Show("Bienvenu cher étudiant");
else
MessageBox.Show("Données invalides !");
cnn.Close();
You must check the username and password on your query or it will return the full table row count, someting like SELECT COUNT(*) FROM Etudiant WHERE User=(username) AND Password=(password).
I'm trying to select just one entry from a database. It is currently returning an xml document object and I can't figure out why. Atleast, thats what my javascript is telling me. I want it to return a string that is the name fo the gameRequestUser where userName="this user"
try {
SqlConnection conn = new SqlConnection(#"Data asdfasdf;database=asdfsdfdf;User id=asdfasdfasdfPassword=asdfasdf;");
SqlCommand getRequest = new SqlCommand("SELECT gameRequestUser FROM UserData Where userName='" + Session["userName"].ToString() + "'", conn);
conn.Open();
SqlDataReader reader = getRequest.ExecuteReader();
while (reader.Read()) {
user = reader.GetValue(0).ToString().Trim();
}
conn.Close();
return user;
} catch (Exception e) { return e.Message.ToString(); }
You should use ExecuteScalar instead of ExecuteReader:
user = (string)getRequest.ExecuteScalar();
And even before you should check your query results using SQL Server Management Studio - run the query there and check if the results are OK.
Always use parameters, you avoid too many problems (string quote, sql injections etc)
using(SqlConnection conn = new SqlConnection("yourconnectionstring"))
{
SqlCommand getRequest = new SqlCommand("SELECT gameRequestUser FROM UserData Where " +
"userName=#user", conn);
conn.Open();
getRequest.Parameters.AddWithValue("#user",Session["userName"].ToString())
SqlDataReader reader = getRequest.ExecuteReader();
while (reader.Read()) {
user = reader.GetValue(0).ToString().Trim();
}
}
One thing you should do is go into SQL Server Management studio, and try running the query there directly:
SELECT gameRequestUser FROM UserData Where userName='this user'
That being said, another thing to keep in mind is you can tell SQL to return to you at most 1 row by doing something like:
SELECT top 1 gameRequestUser FROM UserData Where userName='this user'
I hope this helps!
Use a SELECT TOP 1 ... query
SELECT TOP 1 gameRequestUser FROM UserData WHERE ...
Use SqlCommand's ExecuteScalar() method instead of ExecuteReader(), since you only need one field value returned.
SqlCommand getRequest = new SqlCommand(....);
...
string user = Convert.ToString(cmd.ExecuteScalar());
I get an error in my code: Cannot find table 0. what am I doing wrong?
OdbcCommand cmd = new OdbcCommand("Select * from User where username=? and password=?", cn);
DataSet ds = new DataSet();
//Select the username and password from mysql database in login table
cmd.Parameters.Add("#username", OdbcType.VarChar);
cmd.Parameters["#username"].Value = this.Login1.UserName;
cmd.Parameters.Add("#password", OdbcType.VarChar);
cmd.Parameters["#password"].Value = this.Login1.Password;
//use asp login control to check username and password
//Session["UserID"] = "usrName";
//set the UserID from the User Table unsure how to add this to the sql syntax above
OdbcDataReader dr = default(OdbcDataReader);
// Initialise a reader to read the rows from the login table.
// If row exists, the login is successful
dr = cmd.ExecuteReader();
DataTable dt = ds.Tables[0];
DataRow dp = dt.Rows[0];
if (dt.Rows.Count != 0)
{
Session["UserID"] = Convert.ToString(dp["UserID"]);
e.Authenticated = true;
Response.Redirect("UserProfileWall.aspx");
// Event Authenticate is true forward to user profile
}
}
}
Your code creates an empty dataset, then tries to get a table from it.
Since you never put anything in the dataset, you get an error.
You need to use the DataReader that you got back from your query (use the HasRows property).
However, I strongly recommend that you
Use ASP.Net's built-in forms authentication system
instead. It will save you lots of code and is more secure.
Put User in brackets: [User] - it is a reserved.
I see you're using MySQL - I think it is double quotes then: "User"
Do your parameters need to be in the query the same way?
instead of
"Select * from User where username=? and password=?"
should that be
"Select * from User where username=#username and password=#password",
Edit: this might be way off, it might be something specific to our internal sqlcommand stuff?