for school I need to make a web application with c# and mysql.
In the application there is a registration page but when I click on the button to finish I get a syntax error that says that the execute.nonquery is wrong.
Can somebody help me ?
This is the code:
MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["gpopdrachtConnectionString"].ConnectionString);
string insertQ;
insertQ = "Insert into tblWerknemer(Gebruikersnaam, Vnaam, Fnaam, Wachtwoord, Geboortedatum, Geboorteplaats, E-mailadres, Geslacht, Loon, gsmNummer, Nationaliteit, Gemeente, Postcode, StraatEnNr)";
insertQ += "values(#gbr, #Vn, #Fn, #Ww, #GebD, #GebPl, #Email, #Geslacht, #Loon, #gsm, #Nat, #Gemeent, #Post, #Strtnr)";
insertQ += "Insert into tbldiploma(school,NaamDiploma) Values(#school,#diploma)";
insertQ += "Insert into tblpostcode(postcode,gemeente) Values(#Post,#Gemeent)";
insertQ += "Insert into tblstatuut(omschrijving) Values(#omschrijving)";
MySqlCommand cmd = new MySqlCommand();
//= new MySqlCommand(insertQ, conn);
cmd.CommandText = insertQ;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#gbr", txtgbr.Text);
cmd.Parameters.AddWithValue("#Vn", txtVnaam.Text);
cmd.Parameters.AddWithValue("#Fn", txtfnaam.Text);
cmd.Parameters.AddWithValue("#Ww", txtww.Text);
cmd.Parameters.AddWithValue("#GebD", txtgdatum.Text);
cmd.Parameters.AddWithValue("#GebPl", txtgplaats.Text);
cmd.Parameters.AddWithValue("#Email", txtemail.Text);
cmd.Parameters.AddWithValue("#Geslacht", checkgeslacht.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#diploma", txtdiploma.Text);
cmd.Parameters.AddWithValue("#school", txtschool.Text);
cmd.Parameters.AddWithValue("#Loon", txtloon.Text);
cmd.Parameters.AddWithValue("#omschrijving", txtstatuut.Text);
cmd.Parameters.AddWithValue("#gsm", txtgsm.Text);
cmd.Parameters.AddWithValue("#Nat", txtnat.Text);
cmd.Parameters.AddWithValue("#Gemeent", txtgemeent.Text);
cmd.Parameters.AddWithValue("#Post", txtpost.Text);
cmd.Parameters.AddWithValue("#Strtnr", txtstrt.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
and this is the error:
MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-mailadres, Geslacht, Loon, gsmNummer, Nationaliteit, Gemeente, Postcode, Straat' at line 1'
You problem is a syntax near E-mailadres(the way you wrote it) try changing that to one name like emailaddres or email_adres.the dash(-) is causing you trouble
Related
I'm trying to insert data into two tables via a WPF app with a button that saves the data, but I keep getting this error and I need some help. I've tried many videos, try to change the tables in the database but I can't get it to work but it works on the Viestit table, but not on Viestihistoria. The error is
System.Data.SqlClient.SqlException: 'Incorrect syntax near '#Viestinlahettaja'
Thank you in advance.
SqlConnection conn = new SqlConnection(#"Data Source=MYCOMPUTER\SQLEXPRESS;Initial Catalog=LomakeDB;User ID=***;Password=***");
conn.Open();
SqlCommand cmd1 = new SqlCommand("INSERT INTO Viestit(ID,Kokonimi,Viesti,Viestin_saaja) values(#ID,#Kokonimi,#Viesti,#Viestin_saaja)", conn);
cmd1.Parameters.AddWithValue("#ID", txtbox_ID.Text);
cmd1.Parameters.AddWithValue("#Kokonimi",txtbox_Nimi.Text);
cmd1.Parameters.AddWithValue("#Viesti", txtbox_Viesti.Text);
cmd1.Parameters.AddWithValue("#Viestin_saaja", txtbox_Viestinvastaanottaja.Text);
cmd1.ExecuteNonQuery();
cmd1.Parameters.Clear();
SqlCommand cmd2 = new SqlCommand("INSERT INTO Viestihistoria(ViestiID,Viesti,Viestin_lahettaja) values(#ViestiID,#Viesti2,#Viestinlahettaja", conn);
cmd2.Parameters.AddWithValue("#ViestiID", txtbox_ID.Text);
cmd2.Parameters.AddWithValue("#Viesti2", txtbox_Viesti.Text);
cmd2.Parameters.AddWithValue("#Viestinlahettaja", txtbox_Nimi.Text);
cmd2.ExecuteNonQuery();
cmd2.Parameters.Clear();
MessageBox.Show("Data lähetetty onnistuneesti!");
conn.Close();
You forgot to add closing ) at the end of this line in sql command text:
The corrected line:
SqlCommand cmd2 = new SqlCommand("INSERT INTO Viestihistoria(ViestiID,Viesti,Viestin_lahettaja) values(#ViestiID,#Viesti2,#Viestinlahettaja)", conn);
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();
}
}
I'm quite used to using c# with SQL server. I have no idea why a simple statement would fail to insert data. My code is as follows:
query = "INSERT INTO MCDPhoneNumber ([MCDID],[PhoneNumber])" +
"VALUES("+maxid+", '"+tel+"')";
SqlConnection conn = new SqlConnection("Data Source=source; ...");
SqlCommand newCommand = new SqlCommand(query, conn);
int success= myCommand.ExecuteNonQuery();
if (success!= 1)
{
MessageBox.Show("It didn't insert anything:" + query);
}
First of all let me tell that I know that I should use parameters for data and I initially did, but when it failed I tried a simple query and it still fails. For addition I can tell that I have a similar insert just before that one in another table and it works. What's funnier is that when I copy paste query to SQL Server Management Studio it works. It also doesn't report any error in process.
====================== Edit ===============================
If you wish to use old command object (i.e. myCommand) then use following code instead of creating a new command(newCommand)
myCommand.CommandText = query;
myCommand.CommandType = System.Data.CommandType.Text;
And then execute it
you are binding query with newCommand and executing myCommand.
====================== Edit ===============================
SqlCommand newCommand = new SqlCommand(query, conn);
here you have defined newCommand for SQLCOMMAND object
int success= myCommand.ExecuteNonQuery();
and you are accessing it as myCommand
And moreover i think you are not opening connection
First of all, you define your command as newCommand but you executing your myCommand.
You should always use parameterized queries for your sql queries. This kind of string concatenations are open for SQL Injection attacks.
query = "INSERT INTO MCDPhoneNumber (MCDID, PhoneNumber) VALUES(#maxid, #tel)";
using(SqlConnection conn = new SqlConnection("Data Source=source; Initial Catalog=base; Integrated Security = true"))
{
SqlCommand newCommand = new SqlCommand(query, conn);
conn.Open();
newCommand.Parameters.AddWithValue("#maxid", maxid);
newCommand.Parameters.AddWithValue("#tel", tel);
int success= newCommand.ExecuteNonQuery();
if (success != 1)
{
MessageBox.Show("It didn't insert shit:" + query);
}
}
And please be more polite about your error messages :)
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();
I'm having immense trouble getting a connection to a .sdf (sql compact edition) database. I can connect initially to extract rows in order to verify a username/password, but when I try to add items to the database, either by a SqlCeConnection/SqlCeCommand command or by trying to add items SqlClient/SqlCommand connection, I have no luck. I get:
A network-related or instance-specific error occurred while establishing
a connection to SQL Server. The server was not found or was not accessible.
Verify that the instance name is correct and that SQL Server is configured to
allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error
Locating Server/Instance Specified)
when using:
private void button1_Click_1(object sender, EventArgs e)
{
System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection("Data Source=C:\\Users\\Tim\\Documents\\Visual Studio 2010\\Projects\\Dispatch POS\\Dispatch POS\\GhsDB.sdf");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT [Employee Table] (SSN, FirstName) VALUES ('555-23-4322', 'Tim')";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
or when I try:
System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection("Data Source=C:\\Users\\Tim\\Documents\\Visual Studio 2010\\Projects\\Dispatch POS\\Dispatch POS\\GhsDB.sdf");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT [Employee Table] (SSN, FirstName) VALUES ('555-23-4322', 'Tim')";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
Nothing happens, it seems to work until I check the .sdf file and see nothing has been added. I do not have SQL Server CE installed, though I do have 2008 R2 installed (I'm working on someone else's project).
Right now I'm not worried about the security holes, I'm just trying to successfully add a record. Any help would be much appreciated, as I've spent about three or four hours working on something I figure would take about 20 minutes.
Probably you have found the solution by now, but if you use a sdf file, the assembly you should add a reference to System.Data.SqlServerCe and then something like:
SqlCeConnection sqlConnection1= new SqlCeConnection();
sqlConnection1.ConnectionString = "Data Source = C:\\Users\\Tim\\Documents\\Visual Studio 2010\\Projects\\Dispatch POS\\Dispatch POS\\GhsDB.sdf";
System.Data.SqlServerCe.SqlCeCommand cmd = System.Data.SqlServerCe.SqlCeCommand;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT [Employee Table] (SSN, FirstName) VALUES ('555-23-4322', 'Tim')";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
you most to use sqlceconnection and sqlcecommand classes. like this :
SqlCeConnection conn = new SqlCeConnection(connectionString);
SqlCeCommand cmd = conn.CreateCommand();
conn.Open();