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);
Related
Every time I try to run my code, I get this exception:
An unhandled exception of type 'System.Data.SqlClient.SqlException'
occurred in System.Data.dll
Additional information: Incorrect syntax near ')'.
Tried multiple workarounds, but I never get past the ExectueNonQuery line. Can someone tell me what's wrong with it?
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=CHARLIE-PC\MSSQLSERVER1;Initial Catalog=Tema;Integrated Security=True;");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Fisier (idFisier, Nume, idFolder) VALUES ('"+idFis.Text+ "','"+ numeFis.Text + "','" +idFoldFis.Text +"',)", con);
cmd.ExecuteNonQuery();
con.Close();
}
While the other questions state the root problem, your trailing comma, you really must do better about your queries. Do not glue your query together like that, use parameters instead. If you do not you are opening yourself to huge security problems. Also you really must put the connection in a using statement so when a error does happen the connection will still be closed.
private void button1_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(#"Data Source=CHARLIE-PC\MSSQLSERVER1;Initial Catalog=Tema;Integrated Security=True;"))
{
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Fisier (idFisier, Nume, idFolder) VALUES (#idFis,#numeFis,#idFoldFis)",con);
cmd.Parameters.Add("#idFis", SqlDbType.NVarChar, -1).Value = idFis.Text;
cmd.Parameters.Add("#numeFis", SqlDbType.NVarChar, -1).Value = numeFis.Text;
cmd.Parameters.Add("#idFoldFis", SqlDbType.NVarChar, -1).Value = idFoldFis.Text;
cmd.ExecuteNonQuery();
}
}
The comma is your problem, but I would recommend a few other changes at least before moving on:
Don't embed your connection strings into each db connection request. Use app.config/web.config or anything else :)
Ensure your connections are commands are properly disposed of
Parameterize any SQL queries to prevent injection attacks
Abstract database commands into separate business layer
1. Utilize an "app.config" for connection strings
There are many docs out there on keeping a connection string secure, but at a minimum, don't embed straight into each of your connection code.
Add an "app.config" to your client project (or utilize the web.config of web projects). At a minimum, this looks like this:
<configuration>
<appSettings>
<add key="db" value="Data Source=CHARLIE-PC\MSSQLSERVER1;Initial Catalog=Tema;Integrated Security=True;" />
</appSettings>
</configuration>
Then add a reference to "System.Configuration" to your project, and you can reference it like this in your code:
var con = new SqlConnection(ConfigurationManager.AppSettings["db"]);
2. Ensure your connections ard commands are properly disposed
Wrap connections and commands in using. Here is an example:
using (var con = new SqlConnection(ConfigurationManager.AppSettings["db"]))
{
con.Open();
var sql = "/* My command here */";
using (var cmd = new SqlCommand(sql, con))
{
// SQL execution here
}
} // Closing is now handled for you (even if errors occur)
3. Parameterize any SQL queries to prevent injection attacks
Concatenating strings are very dangerous for SQL commands (just google "SQL Injection"). This is how to protect yourself.
using (var con = new SqlConnection(ConfigurationManager.AppSettings["db"]))
{
con.Open();
var sql = "INSERT INTO Fisier (idFisier, Nume, idFolder) VALUES (#idFisier, #nume, #idFolder)";
using (var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("#idFisier", SqlDbType.VarChar).Value = idFis.Text;
cmd.Parameters.Add("#nume", SqlDbType.VarChar).Value = numeFis.Text;
cmd.Parameters.Add("#idFolder", SqlDbType.VarChar).Value = idFoldFis.Text;
cmd.ExecuteNonQuery();
}
} // Closing is now handled for you (even if errors occur)
4. Abstract database commands into separate business layer
It is usually best practice and will save you many headaches by writing separate classes (even class library) as your business layer that only contain your data commands. Then your UI would only handle calling the business layer methods.
If your database ever changes or you need to do similar functionality in other parts of your UI, it won't be very fun updating the same query all over your UI as opposed to just updating a single spot in your business layer.
Make SQL being readable and parametrized and you'll find the routine easy to implement:
// Extract a method (or even a class): do not mix UI and business logic/storage
// Just RDBMS logic: no UI controls or something at all
private static void CoreInsertFisier(string idFisier, nume, idFolder) {
// Do not hardcode the connection string, but read it (from settings)
// wrap IDisposable into using
using (SqlConnection con = new SqlConnection(ConnectionStringHere)) {
con.Open();
// Make sql readable (use verbatim strings #"...")
// Make sql parameterized
string sql =
#"INSERT INTO Fisier (
idFisier,
Nume,
idFolder)
VALUES (
#prm_idFisier,
#prm_Nume,
#prm_idFolder)";
// wrap IDisposable into using
using (SqlCommand cmd = new SqlCommand(sql, con)) {
// Parameters.Add(...) is a better choice, but you have to know fields' types
cmd.Parameters.AddWithValue("#prm_idFisier", idFisier);
cmd.Parameters.AddWithValue("#prm_Nume", nume);
cmd.Parameters.AddWithValue("#prm_idFolder", idFolder);
cmd.ExecuteNonQuery();
}
}
}
...
private void button1_Click(object sender, EventArgs e) {
// UI: just one call - please insert these three textbox into db
CoreInsertFisier(idFis.Text, numeFis.Text, idFoldFis.Text);
}
You have an extra trailing comma:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=CHARLIE-PC\MSSQLSERVER1;Initial Catalog=Tema;Integrated Security=True;");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Fisier (idFisier, Nume, idFolder) VALUES ('"+idFis.Text+ "','"+ numeFis.Text + "','" +idFoldFis.Text +"')",con);
cmd.ExecuteNonQuery();
con.Close();
}
Anyway as others said, it is a very bad idea to concatenate your query that way, since it could lead you to have sql injection on your code.
Try removing the , before the closing )
SqlCommand cmd = new SqlCommand("INSERT INTO Fisier (idFisier, Nume, idFolder) VALUES ('"+idFis.Text+ "','"+ numeFis.Text + "','" +idFoldFis.Text +"')",con);
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();
}
}
SqlConnection CON = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=D:\\VS_project\\WindowsFormsApplication1\\WindowsFormsApplication1\\myInfo.mdf;Integrated Security=True");
private void button4_Click(object sender, EventArgs e)
{
try
{
CON.Open();
SqlDataAdapter SDA = new SqlDataAdapter("INSERT INTO myInfo(Name,Address,Gender,LangKnownHindi)VALUES('" + textBox1.Text + "','" + textBox2.Text + "','" + Gender + "','" + LANG_Hin + "')", CON);
SDA.SelectCommand.ExecuteNonQuery();
CON.Close();
MessageBox.Show("Saved SuccessFully!!!!!");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
When I run this program I get:
An unhandled exception of type 'System.InvalidOperationException'
occurred in System.Data.dll. Additional information: The connection
was not closed. The connection's current state is open.
Having a SQL connection object exist in a shared scope is a famously bad idea. The connection should be created, used, and disposed within the scope of the operation using it. Otherwise other code may try to use the same connection object (or even this same code more than once), leaving it in an unknown state. Which is very likely what's happening here.
Create the connection in the method itself:
private void button4_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection CON = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=D:\\VS_project\\WindowsFormsApplication1\\WindowsFormsApplication1\\myInfo.mdf;Integrated Security=True"))
{
CON.Open();
SqlDataAdapter SDA = new SqlDataAdapter("INSERT INTO myInfo(Name,Address,Gender,LangKnownHindi)VALUES(#Name,#Address,#Gender,#LangKnownHindi)", CON);
SDA.SelectCommand.Parameters.AddWithValue("#Name", textBox1.Text);
SDA.SelectCommand.Parameters.AddWithValue("#Address", textBox2.Text);
SDA.SelectCommand.Parameters.AddWithValue("#Gender", Gender);
SDA.SelectCommand.Parameters.AddWithValue("#LangKnownHindi", LANG_Hin);
SDA.SelectCommand.ExecuteNonQuery();
CON.Close();
}
MessageBox.Show("Saved SuccessFully!!!!!");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
Important: Also, note that I've done a couple of things here:
Wrapped the SqlConnection object in a using block. This basically creates a try/finally block which ensures that the connection is disposed after it's been used (by calling Dispose() in the finally block, so it only works on IDisposable objects). It's important to ensure disposal of I/O resources.
Replaced your SQL injection vulnerabilities with query parameters. You should always treat user input as parameter values, not as executable SQL code.
You should connect inside the method and handle disconnecting right. The easiest way to do so is by using using, which also disposes your connection handles in created in the background.
Also, in this case a SqlCommand fits the purpose better. Be aware of SQL injection too, since you concatenate user input to your SQL statement. Use parameters instead!
private void button4_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=D:\\VS_project\\WindowsFormsApplication1\\WindowsFormsApplication1\\myInfo.mdf;Integrated Security=True"))
{
conn.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO myInfo(Name,Address,Gender,LangKnownHindi)VALUES(#name, #address,#gender,#lang)", conn))
{
command.Parameters.AddWithValue("#name", textBox1.Text);
command.Parameters.AddWithValue("#address", textBox2.Text);
command.Parameters.AddWithValue("#gender", Gender);
command.Parameters.AddWithValue("#lang", LANG_Hin);
command.ExecuteNonQuery();
}
conn.Close();
MessageBox.Show("Saved SuccessFully!!!!!");
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
Are you sure dat u have used correct denoations of for 'myInfo' means caps nd small letters are in right order??..it is actually having an error in finding d database vid same name..use checkpoints in visual studio to check d execution of your program from starting..if you dont knw how to use checkpoints in visual studio den jst google d same..it vil show u step by step progress of ur code and den when u find error line of code just copy paste d line in sql server..if format of query in database and parameters given by you are correct den it vil execute in database or otherwise it vil fail to execute and vil show you error in sql statement
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
What I need to do is basically take the users name (which is already stored as a variable) and their score (which is also a variable) and store it in my database when they press 'submit'. Here is the code I have for the button click.
private void btnSubmitScore_Click(object sender, EventArgs e)
{
string connStr = "server=server; " +
"database=databasename; " +
"uid=username; " +
"pwd=password;";
MySqlConnection myConn = new MySqlConnection(connStr);
}
Obviously i have changed the login details etc. I have had a look around and have only managed to find confusing codes about how to display data from a database in a form (i will do this later), but for now, i need to know how to add sName and iTotalScore into the database. (Fields are called 'Name' and 'Score' in DB)
You are going to use a combination of SqlConnection, SqlCommand and their properties. the connection is essentially the stuff of your code. The command is a literal SQL statement, or a call to a stored procedure.
A common C# idiom is to form your code around the very first line as shown here:
using (SqlConnection myConnection = new SqlConnection()) {
string doThis = "select this, that from someTable where this is not null";
SqlCommand myCommand = new SqlCommand(dothis, myConnection);
try {
myCommand.Connection.Open();
myReader = myCommand.ExecuteReader(); //pretend "myReader" was declared earlier
} catch (Exception myEx) {
// left to your imagination, and googling.
}
finally {
myCommand.Connection.Close();
}
}
// do something with the results. Your's to google and figure out
The general outline is
Using a connection
instantiate and configure an SqlCommand
Use try/catch as shown.
The "using" block gives use behind the scenes cleanup/disposal of all those objects we don't need anymore when we're done; in particular the SqlConnection object.
You must learn more about these Sqlxxxxx classes, there's lots of ways to configure them to do what you want.
I am not familiar with the MySql connector, but the code should be something along the lines of:
private void Insert()
{
string connStr = "server=server; " +
"database=databasename; " +
"uid=username; " +
"pwd=password;";
string query = "INSERT INTO TableName('Name','Score) VALUES (#name, #score);";
using(MySqlConnection connection = new MySqlConnection(connStr))
{
MySqlCommand insertCommand = new MySqlCommand(connection,command);
insertCommand.Paramaters.AddWithValue("#name",sName);
insertCommand.Paramaters.AddWithValue("#score",iTotalScore);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}