WPF app inserting into multiple tables throws an error - c#

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);

Related

syntax error non query c#

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

Read *.rtf files from database using C#

I tried to read *.rtf files from an database, but I couldn't.
Here is the code which I used to add text in database from richTextBox
SqlConnection con = new SqlConnection(#"Data Source=MARIA-PC;Initial Catalog=Account;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[FILE] (File_name,The_text) VALUES (#File_name,#The_text)", con);
cmd.Parameters.Add("#File_name", textBox1.Text);
cmd.Parameters.AddWithValue("#The_text", richTextBox1.Rtf);
cmd.ExecuteNonQuery();
con.Close();
And the table I created
Click here
I tried a lot of solutions I found on the internet, but none of them where any good.
What I want to do is to display the text saved in database in the blank richTextBox.

Invalid Object Name in ExecuteNonQuery

I'm currently trying to develop an application that allows you to track your spending as part of my class. However I run into the error "Invalid object name 'dbo.AccTransactions"
My Windows Form Code:
string command = "Insert INTO dbo.AccTransactions (id, transact_id, payee, dateof, amount, category)"
+ "Values (#id, #transact_id, #payee, #dateof, #amount, #category)";
SqlCommand cmd = new SqlCommand(command, con);
cmd.Parameters.AddWithValue("#id", 1);
cmd.Parameters.AddWithValue("#transact_id", 2);
cmd.Parameters.AddWithValue("#payee", payeeTextBox.Text);
cmd.Parameters.AddWithValue("#dateof", DateTime.Today);
cmd.Parameters.AddWithValue("#amount", Convert.ToDecimal(amountTextBox.Text));
cmd.Parameters.AddWithValue("#category", categoryTextBox.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
My Connection String:
SqlConnection con = new SqlConnection(#"Data Source=IVY\SQLEXPRESS;Initial Catalog=BudgetTracker;Integrated Security=SSPI;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False");
My database has the table "dbo.AccTransactions" and it performs perfectly in SSMS.
Any assistance would be great!
I guess you are missing database name in the connection string.
SqlConnection con = new SqlConnection(#"Data Source=IVY\SQLEXPRESS;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False");
try it by putting the name of your database in the following string.
SqlConnection con = new SqlConnection(#"Data Source=IVY\SQLEXPRESS; Initial Catalog=YOUR_DATABASE_NAME;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False");
Please check that user who is running your program has an access to that table. Most probably you need to set your user as dbo since you accessing the table as dbo.AccTransactions.

Inserting data into sql server fails with no reason

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 :)

Microsoft Access OleDb Connection Error

I am trying to access an Access 2003 database remotely from my ASP.NET application. My code is:
DataSet dsImportedData = new DataSet();
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=MS Remote;Remote Provider=Microsoft.Jet.OLEDB.4.0;Remote Server=http://myIp;Data source=C:\myDatabase.mdb;";
try
{
System.Data.OleDb.OleDbCommand command = conn.CreateCommand();
command.CommandText = "SELECT * FROM myTable";
conn.Open();
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(command);
adapter.Fill(dsImportedData);
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
However, I am always getting an exception stating: {"[Microsoft][ODBC Microsoft Access Driver] Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'."}
My command is basic, I have no idea what could be wrong with it. Did anyone confront with the same issue? Thanks!
Try this ....
String command = "SELECT * FROM myTable";
conn.Open();
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(command, conn);
adapter.Fill(dsImportedData);
Apparently the error can be caused by the specified table not existing. Just a thought...
Another thought would be to remove the remoting complexity and try to get to the most simple working code, possibly with a new access database just to start to narrow down what is causing the problem.
If you set the command type to Stores procedure it works for me.
command.CommandType = System.Data.CommandType.StoredProcedure;

Categories