This question already has an answer here:
Syntax error in INSERT statement into MS Access
(1 answer)
Closed 7 years ago.
I have already build a successful login form. But I want to have the opportunity to create a new account. I have two textboxes; one for username and one for password. Once the button is clicked, it needs to write this data to a MS Access 2002-2003 database file. But when I click the button I get the following error message:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Syntax error in INSERT INTO statement.
This is the code I am using:
private void buttonRegistreren_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "INSERT INTO Gebruikers (Username, Password) values('" + textBoxUserregist.Text + "', '" + textBoxPassregist.Text + "')";
command.ExecuteNonQuery();
connection.Close();
}
Somebody knows what I am doing wrong?
Password is a reserved keyword in MS-Access, you need to encapsulate it between square brackets
command.CommandText = "INSERT INTO Gebruikers (Username, [Password]) ...."
said that please remember that string concatenations to build sql command is a very bad practice and leads to numerous problems. Start using parameters as soon as possible as in the example below
private void buttonRegistreren_Click(object sender, EventArgs e)
{
using(OleDbConnection cn = new OleDbConnection(.....))
using(OleDbCommand command = new OleDbCommand(#"INSERT INTO Gebruikers
(Username, [Password]) values(#name, #pwd)", cn))
{
cn.Open();
command.Parameters.Add("#name", OleDbType.NVarWChar).Value =textBoxUserregist.Text ;
command.Parameters.Add("#pwd", OleDbType.NVarWChar).Value = textBoxPassregist.Text;
command.ExecuteNonQuery();
}
}
Related
I'm building a user registration page that save user's info into a local database. However I get a SqlException error. Does anyone know what I'm doing wrong here? I'm developing the program in ASP.net and using the local database server.
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegisterConnectionString"].ConnectionString);
conn.Open();
string checkUser = "select count(*) from Table where userName = '" + txtUN.Text + "'";
SqlCommand comm = new SqlCommand(checkUser, conn);
int temp = Convert.ToInt32(comm.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("user already exist");
}
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegisterConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "insert into Table(UserName, name, Address, e-Mail, IC, phone, password) values(#Uname, #name, #add, #mail, #ic, #phone, #pswrd) ";
SqlCommand comm = new SqlCommand(insertQuery, conn);
comm.Parameters.AddWithValue("#Uname", txtUN.Text);
comm.Parameters.AddWithValue("#name", txtName.Text);
comm.Parameters.AddWithValue("#add", txtAdd.Text);
comm.Parameters.AddWithValue("#mail", txtEmail.Text);
comm.Parameters.AddWithValue("#ic", txtIC.Text);
comm.Parameters.AddWithValue("#phone", txtPhone.Text);
comm.Parameters.AddWithValue("#pswrd", txtPsswrd.Text);
comm.ExecuteNonQuery();
Response.Redirect("Default.aspx");
Response.Write("registration was succesful");
conn.Close();
}
catch(Exception ex)
{
Response.Write("error"+ex.ToString());
}
}
You don't give the details of the exception, (ie: exception.Message and exception.InnerException.Message) but from your code I think you have the classical "Syntax Error Near ...."
This is caused by the presence of a reserved keyword in your query text. This reserved keyword is TABLE. You could fix it enclosing the word in square brackets (or better change the name of the table to somenthing more meaningful)
string checkUser = "select count(*) from [Table] where userName = ...";
A part from this, remember to use always parameterized queries also for simple tasks as looking for logins. Last but not least, storing password in clear text inside the database is a big NO-NO from a security standpoint. Everyone, having access to your database using some kind of administrative tool, could look at the passwords of your users, someone could intercept the network traffic between user pc and database server and see the credentials sent by your application. So, please, search for password hashing on this site to find a more secure approach to this problem
I'm trying to create a Registration Page using Webforms that'll connect to a MySQL databse and insert the data, but it throws up an ArgumentException (even though I believe I'm following my tutorial exactly) and will not insert the data into the table.
My C# code for the Registration page is thus:
public partial class Registration : System.Web.UI.Page
{
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
String queryStr;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void registerEventMethod(object sender, EventArgs e)
{
registerUser();
}
private void registerUser()
{
String connString =
System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "";
queryStr = "INSERT INTO seniorschema.registration (Password1, Email, FirstName, LastName, Password2, Code)" +
"VALUES('" + PasswordTextBox1.Text +"','"+ EmailTextbox.Text +"','"+ firstNameTextBox.Text+"','"+ LastNameTextBox.Text + "' ,'"+ PasswordTextBox2.Text +"', '"+ CodeTextBox.Text + "' )";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
cmd.ExecuteReader();
conn.Close();
}
}
And my connection in the WebConfig file is here:
<connectionStrings>
<add name="WebAppConnString"
connectionString="server=localhost;ID=webuser;pwd=password;database=seniorschema;"
providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
Any Help would be most appreciated. Thanks!
I don't know what tutorial you are reading but they should never teach to use string concatenation when building an sql command text.
However, the error you get is from the connectionstring.
You should write
String connString =ConfigurationManager.ConnectionStrings["WebAppConnString"].ConnectionString;
There is also an error in the definition of the connectionstring in the web.config ( a typo?)
It is Uid=.... not ID=....
And here how I would write the code that add the record.
using MySql.Data.MySqlClient;
....
queryStr = #"INSERT INTO seniorschema.registration
(Password1, Email, FirstName, LastName, Password2, Code)
VALUES(#pwd, #email, #first, #last, #pwd2, #code";
using(MySqlConnection conn = new MySqlConnection(connString))
using(MySqlCommand cmd = new MySqlCommand(queryStr, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#pwd",PasswordTextBox1.Text);
cmd.Parameters.AddWithValue("#email",EmailTextbox.Text );
cmd.Parameters.AddWithValue("#first",firstNameTextBox.Text);
cmd.Parameters.AddWithValue("#last",LastNameTextBox.Text );
cmd.Parameters.AddWithValue("#pwd2",PasswordTextBox2.Text );
cmd.Parameters.AddWithValue("#code",CodeTextBox.Text);
int rowAdded = cmd.ExecuteNonQuery();
}
This approach remove the string concatenation with all the complexities required to correctly code the quotes around the values, also removes any possibility of Sql Injection
Finally, but this is really an argument too broad and not immediately linked to your question.
It is a bad practice, from a security standpoint, to store passwords in clear text. If someone could get a copy of or read the registration table, he/she will be able to read the passwords of all users registered. There are proven methods that store an hash of the password to make them unreadable to onlookers
I'm receiving the following error message:
invalidOperationException was unhandled
In the following code:
private void btnInsert_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=DASTGIRKHAN\\SQLEXPRESS;Initial Catalog=DBProject;Integrated Security=True;Pooling=False");
conn.Open();
SqlCommand cmd = new SqlCommand("Insert INTO EmployeeRecord Values(" + tfCode.Text + ",'" + tfName.Text + "','" + tfCell.Text + "','" + tfAdrs + "',)");
cmd.BeginExecuteNonQuery();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Inserted Successfully");
}
InvalidOperationException exception is thrown when you invoke BeginExecuteNonQuery method (msdn) and you not specified "Asynchronous Processing=true" in the connection string.
You should also set connection to your command:
SqlCommand cmd = new SqlCommand("Insert INTO EmployeeRecord Values(" + tfCode.Text + ",'" + tfName.Text + "','" + tfCell.Text + "','" + tfAdrs + "')", conn);
InvalidOperationException
The name/value pair "Asynchronous Processing=true" was not included
within the connection string defining the connection for this
SqlCommand. The SqlConnection closed or dropped during a streaming
operation.
Sorry but your code has many errors. Let me show a different approach
private void btnInsert_Click(object sender, EventArgs e)
{
string cnString = #"Data Source=DASTGIRKHAN\\SQLEXPRESS;
Initial Catalog=DBProject;
Integrated Security=True;";
string cmdText = #"Insert INTO EmployeeRecord
Values(#code,#fname,#cell,#adr)";
using(SqlConnection conn = new SqlConnection(cnString))
using(SqlCommand cmd = new SqlCommand(cmdText, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#code", Convert.ToInt32(tfCode.Text));
cmd.Parameters.AddWithValue("#fname", tfName.Text );
cmd.Parameters.AddWithValue("#cell", tfCell.Text );
cmd.Parameters.AddWithValue("#adr", tfAdrs.Text);
int rowsInserted = cmd.ExecuteNonQuery();
if(rowInserted > 0)
MessageBox.Show("Inserted Successfully");
else
MessageBox.Show("Insert failes");
}
}
The primary cause of your error is stated by the answer of kmatyaszek, but this is just the tip of the iceberg.
You should always use the using statement around your disposable objects like the connection. This will ensure that the connection is closed and disposed also in case of exceptions.
You should use a parameterized query to create your command to avoid Sql Injection and parsing problems. For example, a single quote in the tfName textbox could lead to a Syntax Error.
The call to BeginExecuteNonQuery, excludes the call to ExecuteNonQuery and requires a call to EndExecuteNonQuery.
Finally, the result of ExecuteNonQuery tells you if the insertion is successful.
As a last note, I have remove the Pooling=False from the connection string.
You haven't said anything why do you want avoid his very useful optimization.
I'd print that SQL text. Looks like there's an unbalanced apostrophe to me.
Better yet, use a .NET class that binds parameters for you. Easier and better SQL injection projection, too.
What are tfCode, tfName,tfCell,tfAdrs? I assume they are textbox control?
if so you are using tfAdrs instead of tfAdrs.Text
also assign connection string to the command and remove additional space in
"Integrated security"
Why complicate yourself, use Parameterized Insert instead of concatenation, which its prone to SQL Injection.
SqlCommand command1 = new SqlCommand("INSERT INTO EmployeeRecord VALUES(#tfCode, #tfName, #tfCell, #tfAdrs)", conn);
command1.Parameters.AddWithValue("#tfCode", trCode);
command1.Parameters.AddWithValue("#tfName", tfName);
command1.Parameters.AddWithValue("#tfCell", tfCell);
command1.Parameters.AddWithValue("#tfAdrs", tfAdrs);
After setting up my SqlDataSource on another page to display the values, they come up as 2 blanks for the 2 times I entered test values on the comments page.
I think I'm missing something in getting them into the table in the SQL Server database value?
I'm not sure what information is needed here, so please inform me.
Thanks in advance
EDIT #1 for user request for CODE
protected void btnSend_Click(object sender, EventArgs e)
{
Page.Validate("vld2");
SendMail();
lblMsgSend.Visible = true;
//SQL Server Database
SqlConnection conn; //manages connection to database
SqlCommand cmd; //manages the SQL statements
string strInsert; //SQL INSERT Statement
try
{
//create a connection object
conn = new SqlConnection("Data Source=localhost\\sqlexpress;" +
"Initial Catalog=RionServer;" +
"Integrated Security=True;");
//Build the SQL INSERT Document
strInsert = "INSERT INTO CommentsAdmin (Name,Phone,Email,Comments)"
+ "VALUES(#Name,#Phone,#Email,#Comments);";
//associate the INSERT statement with the connection
cmd = new SqlCommand(strInsert, conn);
//TELL the SqlCommand WHERE to get the data from
cmd.Parameters.AddWithValue("Name", txtName.Text);
cmd.Parameters.AddWithValue("Phone", txtPhone.Text);
cmd.Parameters.AddWithValue("Email", txtEmail.Text);
cmd.Parameters.AddWithValue("Comments", txtComment.Text);
//open the connection
cmd.Connection.Open();
//run the SQL statement
cmd.ExecuteNonQuery();
//close connection
cmd.Connection.Close();
//display status message on the webpage
lblMsgSend.Text = "Thank you for the comment! Please hit the 'Return to Main Page' to return to the Main Page!";
}
catch (Exception ex)
{
lblMsgSend.Text = ex.Message;
}
txtPhone.Text = "";
txtEmail.Text = "";
txtName.Text = "";
txtComment.Text = "";
}
EDIT #2
The values seems to be empty for the Name, Phone, Email, and Comments in the database and when I test the query, so I think it's registering the entries, just not taking the values into the SQL?
EDIT #3
Due to a suggestion by coder and rs, I've done what they've said. And now I get this error.
"String or binary data would be truncated. The statement has been terminated."
The code has been updated as well.
EDIT #4
This question is a follow up for SQL Server Error, 'Keyword not supported 'datasource'.
Remove all the "" similar to this txtPhone.Text = ""; before entering values to SQL as Server you're entering null values to that. So even if you give some values to the textbox it takes predefined NULL values and it dosen't enter either of them.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
Hi I'm trying to get data from a local sql service database to take the input from a user register form. but when i push the button its not recorded onto the serviceable database.
do i need to use execute non query? how would i fix this code up? thanks
using System.Data.Sql;
using System.Data.SqlClient;
namespace Paddle_Power
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
string connection = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\PaddlePower.mdf;Integrated Security=True;User Instance=True";
SqlConnection cn = new SqlConnection(connection);
try
{
cn.Open();
MessageBox.Show("open");
}
catch (Exception)
{
MessageBox.Show("Did not connect");
}
string username = textBox1.Text;
string password = textBox2.Text;
string sqlquery = ("SELECT * FROM User WHERE Username = '" + textBox1.Text + "'");
sqlquery = "INSERT INTO [User] (Username, Password) VALUES ('" + textBox1.Text + "','" + textBox2.Text + "')";
SqlCommand command = new SqlCommand(sqlquery, cn);
command.Parameters.AddWithValue("Username", username);
command.Parameters.AddWithValue("Password", password);
command.Parameters.Clear();
}
}
}
Something along the lines of the following should hopefully do it. There's some room for improvement, but I at least hope it solves the problem you're having.
string connection = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\PaddlePower.mdf;Integrated Security=True;User Instance=True";
object queryResult = null;
using (SqlConnection cn = new SqlConnection(connection))
{
cn.Open(); // Open connection
// SELECT
using (SqlCommand cmd = new SqlCommand("SELECT * FROM User WHERE Username = #Username AND Password = #Password", cn))
{
cmd.Parameters.AddWithValue("#Username", textBox1.Text);
cmd.Parameters.AddWithValue("#Password", textBox2.Text);
queryResult = cmd.ExecuteScalar();
}
// INSERT
using (SqlCommand cmd = new SqlCommand("INSERT INTO [User] (Username, Password) VALUES (#Username, #Password)", cn))
{
cmd.Parameters.AddWithValue("#Username", textBox1.Text);
cmd.Parameters.AddWithValue("#Password", textBox2.Text);
cmd.ExecuteNonQuery(); // or int affected = cmd.ExecuteNonQuery()
}
}
You can requse the first SqlCommand object or create a new one. There's very little difference with either way you choose to do it.
queryResult is just there for storing the result of cmd.ExecuteScalar(). You can map it to an object if you want (when selecting multiple columns) or cast it to a new type (if you're selecting a single column).
The direct answer is yes, you need to execute a non query. You see, you've prepared the command but you have not issued it. jstnasn's example should be very helpful. Take note of the using statements -- these will implicitly close the command when you exit the using statement, thus ensuring that the command is always closed when done.
The same occurs for the SqlConnection -- the using helps make sure that the connection is disposed of properly. However, if your database connection string allows connection pooling, then I believe the using statement will merely kill your object, without actually killing the connection to the database. This is advantageous because you will have lower I/O overhead the next time you need to open a database connection -- you'll just be connecting to an existing TCP/IP socket rather than opening a new on.
You have no parameters, nor do you ever actually send the query to the database
// parameter placeholders defined with #parameter_name
sqlquery = "INSERT INTO [User] (Username, Password) VALUES (#username, #Password);
SqlCommand command = new SqlCommand(sqlquery, cn);
command.Parameters.AddWithValue("#Username", username);
command.Parameters.AddWithValue("#Password", password);
// This will make the query happen on the database.
// It will handle sending the parameters and all that good stuff
// http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx
command.ExecuteNonQuery();