SQLite error unrecognized token Unity - sqlite

I am using Unity, here is a little snippet of my code. All I want to do is to put the data.token and the data.expire into SQLite. For some reason it keeps throwing me an error that is:
SqliteException: SQLite error
unrecognized token: "587503bc773a565d52401c87"
Mono.Data.Sqlite.SQLite3.Prepare (Mono.Data.Sqlite.SqliteConnection cnn, System.String strSql, Mono.Data.Sqlite.SqliteStatement previous, UInt32 timeoutMS, System.String& strRemain)
Mono.Data.Sqlite.SqliteCommand.BuildNextCommand ()
I have no idea how the token is unrecognized, In SQLite the Token field is a STRING and the Expire field is an INTEGER.
IncomingTokenData data = IncomingTokenData.CreateFromJSON(www.text);
string conn = "URI=file:" + Application.dataPath + "/MyDataBase.s3db"; //Path to database.
var sqlQuery = "INSERT INTO MyDataBase(Token, Expire) VALUES(" + data.token +", " + data.expire + ")";
if(!string.IsNullOrEmpty(www.error)) {
ErrText.text = "Error: " + www.error;
}else{
if(data.pass == "1"){
IDbConnection dbconn;
dbconn = (IDbConnection) new SqliteConnection(conn);
dbconn.Open(); //Open connection to the database.
IDbCommand dbcmd = dbconn.CreateCommand();
dbcmd.CommandText = sqlQuery;
dbcmd.ExecuteNonQuery();

In SQL queries, you should enclose string values in single quotes (in this case, place quotes around data.token):
var sqlQuery = "INSERT INTO MyDataBase(Token, Expire) VALUES('" + data.token +"', " + data.expire + ")";
Note that string concatenation isn't the best way to build up SQL queries - a more robust way to avoid these problems is to use placeholders, like the built-in functionality IDbCommand has for adding parameters:
var sqlQuery = "INSERT INTO MyDataBase(Token, Expire) VALUES(#token, #expire)";
if(!string.IsNullOrEmpty(www.error)) {
ErrText.text = "Error: " + www.error;
}else{
if(data.pass == "1"){
IDbConnection dbconn;
dbconn = (IDbConnection) new SqliteConnection(conn);
dbconn.Open(); //Open connection to the database.
IDbCommand dbcmd = dbconn.CreateCommand();
dbcmd.Parameters.Add("#token", SqlDbType.VarChar).Value = data.token;
dbcmd.Parameters.Add("#expire", SqlDbType.Int).Value = data.expire;
dbcmd.CommandText = sqlQuery;
dbcmd.ExecuteNonQuery();
Using this method, the values are properly formatted according to their data type.

Related

Sqlite code not displaying any Debug log?

Very new to sqlLite and trying to make a very simple bit of code which will display the values of username and password in the table just using the debug log for ease. When running the code nothing is display in the debug log. Could someone suggest a fix?
IDbConnection dbconn;
dbconn = (IDbConnection)new SqliteConnection(conn);
dbconn.Open(); //Open connection to the database.
IDbCommand dbcmd = dbconn.CreateCommand();
string sqlQuery = "SELECT username, password " + "FROM user";
dbcmd.CommandText = sqlQuery;
IDataReader reader = dbcmd.ExecuteReader();
while (reader.Read())
{
string username = reader.GetString(0);
string password = reader.GetString(1);
Debug.Log("Username: " + username + " Password:" + password);
}
reader.Close();
reader = null;
dbcmd.Dispose();
dbcmd = null;
dbconn.Close();
dbconn = null;
}
}
You can try to get the parameter out of the reader like that:
IDataReader reader = dbcmd.ExecuteReader();
while (reader.Read())
{
string username = reader["username"];
string password = reader["password"]
Debug.Log("Username: " + username + " Password:" + password);
}

"Incorrect syntax near 'admin'

this programm when i enter username and password go to data base and compare from table,but when i enter username admin ,password admin(exist in table)
compalier show error "Incorrect syntax near 'admin'" in line
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\1\Documents\DB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
conn.Open();
string checkuser = "select count(*) from [Users] where Username '" + TextBoxUserName.Text + "'";
SqlCommand com = new SqlCommand(checkuser,conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkpassword = "select Password from Users where Password'" + TextBoxPassword.Text + "'";
SqlCommand passComm = new SqlCommand(checkpassword, conn);
string password = passComm.ExecuteScalar().ToString();
if (password == TextBoxPassword.Text)
{
//Session["NEW"] = TextBoxUserName.Text;
Response.Redirect("Welcome.aspx");
}
else
{
Response.Redirect("Error.aspx");
}
}
The error is simply caused by the missing equals before the values concatenated in the sql command text.
But also fixing it, your code is wrong for other reasons.
You should ALWAYS use a parameterized query to avoid Sql Injection and parsing problems,
You could remove the COUNT function that causes an unnecessary load of all records just to confirm the existence of your searched data
You need to identify your user searching for both password and
username on the SAME record, as it is now, the code above search first the username
and then a password, but I can type an existing user name (first if passed) and use
a password of a different user (second if passed) and then gain access to
your site.
.
string checkuser = "IF EXISTS(select 1 from [Users] where Username = #usr AND Password=#pwd)
SELECT 1 ELSE SELECT 0";
using(SqlConnection conn = new SqlConnection(....))
using(SqlCommand com = new SqlCommand(checkuser,conn))
{
conn.Open();
com.Parameters.AddWithValue("#usr", TextBoxUserName.Text);
com.Parameters.AddWithValue("#pwd", TextBoxPassword.Text);
int temp = Convert.ToInt32(com.ExecuteScalar());
if (temp == 1)
Response.Redirect("Welcome.aspx");
else
Response.Redirect("Error.aspx");
}
Other things changed in the example above are the USING STATEMENT to be sure that your connection and command are disposed at the end of the operation also in case of exceptions
Try changing this line
string checkuser = "select count(*) from [Users] where Username '" + TextBoxUserName.Text + "'";
to this
string checkuser = "select count(*) from [Users] where Username = '" + TextBoxUserName.Text + "'";
you are missing an = sign
you'll need to do the same to your password select as well, you also missed the = sign there.
string checkpassword = "select Password from Users where Password = '" + TextBoxPassword.Text + "'";
When checking the Password, you should also include the UserName:
string checkpassword = "select Password from Users where UserName = '" + TexBoxUserName.Text + "' AND Password = '" + TextBoxPassword.Text + "'";
If you do not include the UserName the it is only validating that some user has that password.
The following code will prevent SQL injection by paramterizing the command text
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\1\Documents\DB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
conn.Open();
string checkuser = "SELECT Count(UserName) FROM USERS WHERE UserName = #UserName";
SqlCommand com = new SqlCommand(checkuser,conn);
SqlParameter parmUserName = new SqlParameter("UserName", TextBoxUserName.Text);
com.Parameters.Add(parmUserName);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkpassword = "SELECT Password FROM USERS WHERE UserName = #UserName AND Password = #Password";
SqlCommand passComm = new SqlCommand(checkpassword, conn);
SqlParameter parmPassword = new SqlParameter("Password", TextBoxPAssword.Text);
com.Parameters.Add(parmUserName);
com.Parameters.Add(parmPassword);
string password = passComm.ExecuteScalar().ToString();

executescalar returning null value

string checkuserQuery = "select username from usersign where Username=' " + TextBox1.Text + " ' ";
SqlCommand usercom = new SqlCommand(checkuserQuery, conn);
string user1 = string.Empty;
Object val = usercom.ExecuteScalar();
if (val != null)
{
user1 = val.ToString();
if (user1 == TextBox1.Text)
{
string checkpasswordQuery = "select password from usersign where Username=' " + TextBox1.Text + " ' ";
SqlCommand passcom = new SqlCommand(checkpasswordQuery, conn);
string password = passcom.ExecuteScalar().ToString();
if (password == TextBox2.Text)
{
Session["New"] = TextBox1.Text;
Label5.Text = "password is correct";
Response.Redirect("user.aspx");
}
else
{
Label5.Text = "password is not correct";
}
}
}
else
{
Label5.Text = "val is null";
}
}
ExecuteScalar() will return null if the query doesn't return a value.
Returns the first column of the first row in the result set, or a null
reference (Nothing in Visual Basic) if the result set is empty.
Source
This line will throw a null reference exception:
passcom.ExecuteScalar().ToString();
Building queries using string concatenation is error prone. More importantly, it is vulnerable to SQL injection. The code suggests that passwords are stored in the database in plain text.
SQL injection and plain text passwords are a serious concern for any application. Parameterize your queries (it is very easy with ADO.Net) and hash your passwords.
The lack of a match is probably caused by the following line:
string checkpasswordQuery = "select password from usersign where Username=' " + TextBox1.Text + " ' ";
Note the extra spaces added in the string concatenation. Whatever is in TextBox1 will be preceded/followed by whitespace, causing the match to fail.
the problem could be the space characters in the following (i have put a * where space
is incorrectly used)
where Username='*" + TextBox1.Text + "*' "
So the above will mean that your query is trying to get a user name that has
a space character in start and at the end, so just remove those spaces
another point is, such query should be used with parameters as it is prone to
SQL injection type of attacks

Insert data into database in ASP.NET throwing exception

I'm trying to insert data into database in ASP.NET with this code:
string conn = "TJLDatabaseConnectionString";
conn = ConfigurationManager.ConnectionStrings["Conn"].ToString();
SqlConnection objsqlconn = new SqlConnection(conn);
objsqlconn.Open();
SqlCommand objcmd = new SqlCommand("Insert into MeterReading(MachineName,LastReading,CurrentReading,Consumption) Values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "')", objsqlconn);
objcmd.ExecuteNonQuery();
//MessageBox.Show("Successful");
But when I run it. It gives the following message:
First the important, always use sql-parameters to prevent sql-injection. Never concatenate parameters into a sql-query. This can also solve localization or "escaping" issues.
Also, use the using statement to ensure that anything using unmanaged resources (like a sql-connection) will be closed and disposed even on error:
string sql = #"
INSERT INTO MeterReading(MachineName,LastReading,CurrentReading,Consumption)
VALUES(#MachineName,#LastReading,#CurrentReading,#Consumption)";
using(var objsqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ToString()))
using (var cmd = new SqlCommand(sql, objsqlconn))
{
cmd.Parameters.AddWithValue("#MachineName", TextBox1.Text);
cmd.Parameters.AddWithValue("#LastReading", TextBox2.Text);
cmd.Parameters.AddWithValue("#CurrentReading", TextBox3.Text);
cmd.Parameters.AddWithValue("#Consumption", TextBox4.Text);
objsqlconn.Open();
int insertedCount = cmd.ExecuteNonQuery();
}
Side-note: if you have an identity column and you want to retrieve the newly created primary-key, use SCOPE_IDENTITY and ExecuteScalar even if you use INSERT INTO:
string sql = #"
INSERT INTO MeterReading(MachineName,LastReading,CurrentReading,Consumption)
VALUES(#MachineName,#LastReading,#CurrentReading,#Consumption);
SELECT CAST(scope_identity() AS int)";
//...
int newID = (int)cmd.ExecuteScalar();
Use a variable to check if row is getting affected or not
rowAffected= objcmd.ExecuteNonQuery();
if(rowAffected >0)
{
//sucessful
}
else
{
//
}
Since there is no any exception mention in your question so just for a better and readable code I would suggest you too use using blocks. It gives you nice, cleaner and readable code and also handle objects when they go out of scope.
This is meant for good practices that we generlly follow while coding. Kindly show us the exception for appropriate solution.
private void ConnectToDb()
{
var conn = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
using( var conn = new SqlConnection(conn))
{
conn.Open();
var cmdtxt ="Insert into MeterReading(MachineName,LastReading,CurrentReading,Consumption)
Values(#P1,#P2,#P3,#P4)";
using(var cmd = new SqlCommand(cmdtxt, conn))
{
cmd.CommandType=CommandType.Text;
cmd.Parameters.AddWithValue("#P1", TextBox1.Text);
cmd.Parameters.AddWithValue("#P2", TextBox2.Text);
cmd.Parameters.AddWithValue("#P3", TextBox3.Text);
cmd.Parameters.AddWithValue("#P4", TextBox4.Text);
cmd.ExecuteNonQuery();
}
con.close();
}
}

Sql to update table

I am using the following code to update the user information but i am getting error. Can anybody point me out what is wrong. I am writing this code for web service.
public string UpdateUser(int uID, string fName,
string lName, string password, string emailAddress)
{
// Create connection object
int ix = 0;
string rTurn = "";
OleDbConnection oleConn = new OleDbConnection(connString);
try
{
oleConn.Open();
string sql = "UPDATE [User] SET [fName]=#fName, [lName]=#lName, [password]=#password, [emailAddress]=#emailAddress" + "WHERE [ID]=#uID";
OleDbCommand oleComm = new OleDbCommand(sql, oleConn);
oleComm.Parameters.Add("#fName", OleDbType.Char).Value = fName;
oleComm.Parameters.Add("#lName", OleDbType.Char).Value = lName;
oleComm.Parameters.Add("#password", OleDbType.Char).Value = password;
oleComm.Parameters.Add("#emailAddress", OleDbType.Char).Value = emailAddress;
oleComm.Parameters.Add("#uID", OleDbType.Integer).Value = uID;
ix = oleComm.ExecuteNonQuery();
if (ix > 0)
rTurn = "User Updated";
else
rTurn = "Update Failed";
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
rTurn = ex.ToString();
}
finally
{
oleConn.Close();
}
return rTurn;
}
Error
*I am getting following error when i try to update user.*
<string>
System.Data.OleDb.OleDbException: Syntax error (missing operator) in query expression '#emailAddressWHERE [ID]=#uID'.
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at UserManagement.UserRegistration.UpdateUser(Int32 uID, String fName, String lName, String password, String emailAddress) in C:\Users\smartamrit\Desktop\SystemSoftware\UserManagement\UserRegistration.asmx.cs:line 97
</string>
you need to add extra space before WHERE
string sql = #"UPDATE [User]
SET [fName]=#fName,
[lName]=#lName, [password]=#password,
[emailAddress]=#emailAddress" + " WHERE [ID]=#uID";
^ here
or I can't see any difference if you didn't concatenate it, why not do it directly
string sql = #"UPDATE [User]
SET [fName]=#fName,
[lName]=#lName,
[password]=#password,
[emailAddress]=#emailAddress
WHERE [ID]=#uID";
The error is pretty self-explanatory:
'#emailAddressWHERE [ID]=#uID'
You have no space between #emailAddress and WHERE
You need a space before the WHERE here
#emailAddress" + " WHERE
You need add space before your where starts.
You can write your query like this as mentioned below.
string sql = "UPDATE [User] SET [fName]=#fName, [lName]=#lName,
[password]=#password, [emailAddress]=#emailAddress" +" "+ "WHERE [ID]=#uID";

Resources