I want to insert email in Table with only one column. I tried on 2 way. First time I tried with commandText and second time I tried with parapeters. But the both solution give me the same error.
System.Data.OleDb.OleDbException: 'Syntax error in INSERT INTO statement.'
I don't see any error in INSERT STATEMENT. Maybe the problem is in TABLE?
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT COUNT (email) FROM [User] WHERE [email] LIKE '" + userEmail + "';";
conn.Open();
int count = Convert.ToInt32(cmd.ExecuteScalar()); // This passed
if (count == 0)
{
string query = #"INSERT INTO User (email) VALUES (#email)";
string cmdText= #"INSERT INTO User (email) VALUES ('"+userEmail+"')";
OleDbCommand command = new OleDbCommand(cmdText, conn);
// command.Parameters.AddWithValue("#email", "userEmail");
// command.CommandText = query;
command.ExecuteNonQuery(); // I GOT ERROR HERE
}
conn.Close();
}
User is a keyword. You should INSERT INTO [USER] instead
string cmdText= #"INSERT INTO User (email)) VALUES ('"+userEmail+"')";
you have one ')' too many after (email)
Related
Complete Code For stopping user from using same User Names
if (IsPostBack)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
string checkuser = "select count(*) from UserDataTable where UserName='" +
username.Text + "'";
SqlCommand com = new SqlCommand(checkuser, con);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User Already Exists");
}
con.Close();
}
}
The above code is for stopping people to use the same UserName that
is already used to register
But unfortunately it does not stop them from registration with the existing
username, hence they can still use the same User Name.
Code For Button1_Click
This is the code for my submit button
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
con.Open();
//inserting data to database
string insertQuery = "insert into [UserDataTable] (UserName,Email,Password,Country) values (#username, #email, #password, #country)";
SqlCommand com = new SqlCommand(insertQuery, con);
com.Parameters.AddWithValue("#username", username.Text);
com.Parameters.AddWithValue("#email", email.Text);
com.Parameters.AddWithValue("#password", password.Text);
com.Parameters.AddWithValue("#country", DropDownList1.SelectedItem.ToString());
com.ExecuteNonQuery();
Response.Redirect("Manager.aspx");
Response.Write("You're Now Registered");
con.Close();
}
catch(Exception ex)
{
Response.Write("Error:"+ex.ToString());
}
My DataBase
My database that i created
CREATE TABLE [dbo].[UserDataTable] (
[Id] INT NULL,
[UserName] NVARCHAR (50) NULL,
[Email] NCHAR (50) NULL,
[Password] NCHAR (20) NULL,
[Country] NCHAR (15) NULL
My Problem/Question:
why is it not stopping them from using the existing Username
i wrote this code by dissecting other codes that i saw online, So if it seems strange and weird I apologize its my first time using C#
Hope this helps in understanding my problem
Software:Visual Studio 2017
Try running that query and seeing what you get back. It's possible that you're getting different results than you expect.
I'd recommend changing:
if (temp == 1)
to:
if (temp > 0)
which should weed out cases where a username is already in the database twice.
Also, as other people have mentioned in comments, you definitely want to be using parameters. Here is your code converted to use parameters:
string checkuser = "select count(*) from UserDataTable where UserName = #userName";
SqlCommand com = new SqlCommand(checkuser, con);
com.Parameters.Add(new SqlParameter("#userName", username.Text));
int temp = Convert.ToInt32(com.ExecuteScalar());
Firstly get rid of SQL-Injection :
string checkuser = "select * from UserDataTable where UserName=#uname";
Then use either a DataTable or a DataReader.Let's use DataReader for instance :
////Firstly,we generally declare the connection as con for easy-recognition
SqlConnection con = new SqlConnection;
con = "connectionstringhere";
///then we use the sqlCommand which we generally declare as cmd
SqlCommand cmd = new SqlCommand(checkuser,con);
cmd.Parameters.Add("#uname",SqlDbType.Varchar).Value = usernameStringHere
///then we use a datareader(note: A datareader is better than DataAdapter regarding performance
SqlDataReader dr;
dr = cmd.ExecuteReader;
///Then we check if any row exists in the dataReader after we filter the database
If dr.Hasrows
{
////Wont save data
}
The above code will get the job done.
Or you can simply go with ExecuteScalar
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) from UserDataTable where userNme=#uname",con)
cmd.Parameters.Add("#uname",SqlDbType.VarChar).Value = usernamestringhere
int count = (int)cmd.ExecuteScalar;
If(count > 0)
{
///eon't save data
}
Summary : You had two issues :
1 . Sql-Injection - which i clearly explained how to fix
2 . using temp == 1 instead of temp > 0..
Hope this helps you
99.9999999% chance "UserName" is not a primary key.
Just run a select to see if there are multiple users with the input "UserName".
a quick fix
change
select count(*) from...
to
select top 1 1 from...
It will always return 1 if there is anything matches, NULL if not.
I am writing a sample application to insert data into a SQL Server database using C#. Data is not persisting in the database.
Below is my code:
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "Insert into Record (ID,Name) values ('" + txtId.Text + "' , '" + txtName.Text + "')";
cmd.ExecuteNonQuery();
//cmd.Clone();
conn.Close();
The values are not persisted. There is no error when I insert the values. When I changed my command to:
"Insert into Database.dbo.Record (ID,Name) values ('"
it throws an exception:
Incorrect syntax near the keyword 'Database'.
Why is my SQL Server database not being updated?
Your code as is, is possibly open to SQL injection - you should use parameters.
Also check the table names and primary keys, e.g. if ID is an Identity column it is automatically generated when you insert, so then you'll just INSERT INTO Record (Name) VALUES ('Bob')
Otherwise if ID is a primary key you'll likely have to check you are not trying to insert duplicates.
Please use parameters! (adjust the SqlDbType's if needed)
You should also use a using statement over the connection to properly dispose resources, and ideally use a transaction for updates:
string sqlQuery = "INSERT INTO Record (ID, Name) VALUES (#id, #name); ";
using (SqlConnection conn = new SqlConnection(connectionString)) {
conn.Open();
SqlTransaction tran = conn.BeginTransaction();
try {
SqlCommand command = new SqlCommand(sqlQuery, conn, tran);
SqlParameter in1 = command.Parameters.Add("#id", SqlDbType.NVarChar);
in1.Value = txtId.Text;
SqlParameter in2 = command.Parameters.Add("#name", SqlDbType.NVarChar);
in1.Value = txtName.Text;
command.ExecuteNonQuery();
tran.Commit();
} catch (Exception ex) {
tran.Rollback();
//...
}
}
I have two tables, one containing names, and one containing rates and other data that is lined to each name. After I insert a new name into table A, I want to get the newly auto generated PK to now use to insert into my other table B with rates.
How can I do this? I read about scope_identity online but I'm not sure how to use it.
This is what I have so far:
SqlConnection con = new SqlConnection(pubvar.x);
SqlCommand command = con.CreateCommand();
command.CommandText ="Insert into A values('" +Name + "')";
SqlCommand command2 = con.CreateCommand();
command2.CommandText = "Insert into B values(....)";
SELECT SCOPE_IDENTITY();
con.Open();
command.ExecuteNonQuery();
con.Close();
Considering the case you've described, I don't see any need to return the identity from the database. You can simply issue both statements in one command:
using (var cnx = new SqlConnection(pubvar.x))
using (var cmd = new SqlCommand
{
Connection = cnx,
CommandText = #"
insert into A (Name) values (#name)
insert into B (A_ID, Rate) values (scope_identity(), #rate)
",
Parameters =
{
new SqlParameter("#name", name),
new SqlParameter("#rate", .5m) //sample rate
}
})
{
cnx.Open();
cmd.ExecuteNonQuery();
}
Access 2003
VS 2010 C#
As subject title says I am having problems with. This is related to my previous question I asked, Here. I hope the mod's will be OK with this thread but I am not sure.
Martin Parkin advised not to close the connection between Insert and Select when using ##Identity with C# and MS-Access. I thought I got it working until I discovered that was not the case. To be honest I don't know how to solve this issue. So if anyone can help me I would appreciate it.
This is my btnLogin method..
cmd.CommandText = "INSERT INTO LoginLogTable (UserName, LoggedInDate, LoggedInTime) VALUES (#UserName, #LoggedInDate, #LoggedInTime)";
cmd.Parameters.AddWithValue("#UserName", txtUserName.Text);
cmd.Parameters.AddWithValue("#LoggedInDate", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("#LoggedInTime", DateTime.Now.ToString("HH:mm"));
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT #ID = ##IDENTITY";
// cmd.Parameters.AddWithValue("#ID", OleDbType.WChar); << tried this, unsuccessful
int id = (int)cmd.ExecuteScalar(); // getting the same error?
myCon.Close();
This is my btnLogOut method...
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
int id = 0;
cmd.CommandText = " UPDATE [LoginLogTable] SET [LoggedOutDate] = #LoggedOutDate, [LoggedOutTime] = #LoggedOutTime WHERE [ID] = #ID";
cmd.Parameters.AddWithValue("#ID", id);
cmd.Parameters.AddWithValue("#LoggedOutDate", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("#LoggedOutTime", DateTime.Now.ToString("HH:mm"));
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
Close();
Or
In the btnLogin method if I do
cmd.CommandText = "SELECT #ID = ##IDENTITY";
and hide the cmd.ExecuteNonQuery(); after it. Then date and time will get logged in the database but the date and time will not get saved in the database, for logging out.
I am not sure if the problem is with btnLogin method or btnLogOut method, or both.
Working Solution
Originally I did
cmd.CommandText = " UPDATE [LoginLogTable] SET [LoggedOutDate] = #LoggedOutDate,
[LoggedOutTime] = #LoggedOutTime WHERE [ID] = #ID";
cmd.Parameters.AddWithValue("#ID", id);
cmd.Parameters.AddWithValue("#LoggedOutDate", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("#LoggedOutTime", DateTime.Now.ToString("HH:mm"));
Then I did this
cmd.CommandText = " UPDATE [LoginLogTable] SET [UserName] = #UserName, [LoggedOutDate] =
#LoggedOutDate, [LoggedOutTime] = #LoggedOutTime WHERE ID = #ID";
cmd.Parameters.AddWithValue("#UserName", txtUserName.Text);
cmd.Parameters.AddWithValue("#LoggedOutDate", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("#LoggedOutTime", DateTime.Now.ToString("HH:mm"));
cmd.Parameters.AddWithValue("#ID", id);
Thanks to D Stanley and Gord Thompson.
The #ID variable does not persist in the database the way you seem to think it does. It will go out of scope when the connection is closed (possibly sooner). I would advise that you store the new identity within your application instead:
Assuming these are button handlers that are methods on the form, you could store the ID as a property of the form:
// somewhere in the form definition:
private int ID {get; set;}
...
cmd.CommandText = "SELECT ##IDENTITY";
int id = (int)cmd.ExecuteScalar();
this.ID = id;
Then use the ID in your Logout method:
// get the id from the form
int id = this.ID;
cmd.CommandText = " UPDATE [LoginLogTable] SET [LoggedOutDate] = #LoggedOutDate, [LoggedOutTime] = #LoggedOutTime WHERE [ID] = #ID";
cmd.Parameters.AddWithValue("#ID", id);
cmd.Parameters.AddWithValue("#LoggedOutDate", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("#LoggedOutTime", DateTime.Now.ToString("HH:mm"));
i have database in access with auto increase field (ID).
i insert record like this (in C#)
SQL = "insert into TermNumTbl (DeviceID,IP) values ('" + DeviceID + "','" + DeviceIP + "') ";
OleDbCommand Cmd = new OleDbCommand(SQL, Conn);
Cmd.ExecuteNonQuery();
Cmd.Dispose();
Conn.Close();
how to get the last inserting number ?
i dont want to run new query i know that in sql there is something like SELECT ##IDENTITY
but i dont know how to use it
thanks in advance
More about this : Getting the identity of the most recently added record
The Jet 4.0 provider supports ##Identity
string query = "Insert Into Categories (CategoryName) Values (?)";
string query2 = "Select ##Identity";
int ID;
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("", Category.Text);
conn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = query2;
ID = (int)cmd.ExecuteScalar();
}
}
I guess you could even write an extension method for OleDbConnection...
public static int GetLatestAutonumber(
this OleDbConnection connection)
{
using (OleDbCommand command = new OleDbCommand("SELECT ##IDENTITY;", connection))
{
return (int)command.ExecuteScalar();
}
}
I like more indicate the type of command
is very similar to the good solution provided by Pranay Rana
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql_Insert;
cmd.ExecuteNonQuery();
cmd.CommandText = sql_obtainID;
resultado = (int)comando.ExecuteScalar();
}
query = "Insert Into jobs (jobname,daterecieved,custid) Values ('" & ProjectNAme & "','" & FormatDateTime(Now, DateFormat.ShortDate) & "'," & Me.CustomerID.EditValue & ");"'Select Scope_Identity()"
' Using cn As New SqlConnection(connect)
Using cmd As New OleDb.OleDbCommand(query, cnPTA)
cmd.Parameters.AddWithValue("#CategoryName", OleDb.OleDbType.Integer)
If cnPTA.State = ConnectionState.Closed Then cnPTA.Open()
ID = cmd.ExecuteNonQuery
End Using
Using #Lee.J.Baxter 's method (Which was great as the others id not work for me!) I escaped the Extension Method and just added it inline within the form itself:
OleDbConnection con = new OleDbConnection(string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='{0}'", DBPath));
OleDbCommand cmd = con.CreateCommand();
con.Open();
cmd.CommandText = string.Format("INSERT INTO Tasks (TaskName, Task, CreatedBy, CreatedByEmail, CreatedDate, EmailTo, EmailCC) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", subject, ConvertHtmlToRtf(htmlBody), fromName, fromEmail, sentOn, emailTo, emailCC);
cmd.Connection = con;
cmd.ExecuteScalar();
using (OleDbCommand command = new OleDbCommand("SELECT ##IDENTITY;", con))
{
ReturnIDCast =(int)command.ExecuteScalar();
}
NOTE: In most cases you should use Parameters instead of the string.Format() method I used here. I just did so this time as it was quicker and my insertion values are not coming from a user's input so it should be safe.
Simple,
What we do in excel for copy text in above cell?
Yes, just ctrl+" combination,
and yes, it's work in MS ACCESS also.
You can use above key stroke combination for copy above records field text, just make sure if you have duplicate verification applied or edit field data before move next field.
If you aspects some more validation or any extraordinary then keep searching stack overflow.