I get
SqlException: incorrect syntax near nvarchar
Incorrect syntax near 'ID'
in my code. Please can somebody help me solve it?
My code is
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
SqlCommand cmd;
SqlConnection con = new SqlConnection(#"Data Source=HAIER-PC;Initial Catalog=PDCS;Integrated Security=True");
SqlDataAdapter SDA;
private void button3_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("INSERT INTO CusUtil(Customer ID, Age, Experience, Preferred Alternatives, Outer Shell, Base Gasket, Vent, Vent Type, Impact Absorbent Liner, Eyeport Gasket, Face Shield, Comfort Liner, Chin Strap, Weight, Estimated Price)
VALUES(#Customer ID, #Age, #Experience, #Preferred Alternatives, #Outer Shell, #Base Gasket, #Vent, #Vent Type, #Impact Absorbent Liner, #Eyeport Gasket, #Face Shield, #Comfort Liner, #Chin Strap, #Weight, #Estimated Price)", con);
cmd.Parameters.Add("#Customer ID", textBox1.Text);
cmd.Parameters.Add("#Age", comboBox1.SelectedItem.ToString());
cmd.Parameters.Add("#Experience", comboBox2.SelectedItem.ToString());
cmd.Parameters.Add("#Preferred Alternatives", comboBox3.SelectedItem.ToString());
cmd.Parameters.Add("#Outer Shell", textBox2.Text);
cmd.Parameters.Add("#Base Gasket", textBox3.Text);
cmd.Parameters.Add("#Vent", textBox4.Text);
cmd.Parameters.Add("#Vent Type", textBox5.Text);
cmd.Parameters.Add("#Impact Absorbent Liner", textBox6.Text);
cmd.Parameters.Add("#Eyeport Gasket", textBox7.Text);
cmd.Parameters.Add("#Face Shield",textBox8.Text);
cmd.Parameters.Add("#Comfort Liner",textBox9.Text);
cmd.Parameters.Add("#Chin Strap",textBox10.Text);
cmd.Parameters.Add("#Weight",textBox11.Text);
cmd.Parameters.Add("#Estimated Price",textBox12.Text);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
The error occurs at ExecuteNonQuery. The code simply save the data into a SQL Server database.
In mysql the use of space in column name is allowed but the column name must be wrapped with backticks .. so just for let the user see the command with backtics
but as suggested by Uuerdo .. the space in parameter should be not used ... try using an underscore (or camel case)
`
cmd = new SqlCommand("INSERT INTO CusUtil(`Customer ID`,
Age,Experience,`Preferred Alternatives`,`Outer Shell`,`Base
Gasket`,Vent,`Vent Type`,`Impact Absorbent Liner`,`Eyeport Gasket`
,`Face Shield`,`Comfort Liner`,`Chin Strap`,Weight,`Estimated
Price`)VALUES(#Customer_ID,#Age,#Experience,#Preferred_Alternatives,
#Outer_Shell,#Base_Gasket,#Vent,#Vent_Type,#Impact_Absorbent_Liner,
#Eyeport_Gasket,#Face_Shield,#Comfort_Liner,
#Chin_Strap,#Weight,#Estimated_Price)",con);
in SQLSERVER use [] instead of ``
COuld you please add [ ] - square braces for column with spaces and remove spaces on Parameters. that will help, because all depends the mode you set on mySQL
I am creating a practice SQL Server database project, and I'm trying to enter text into a SQL Server database through a Windows Form. I'm not sure if my text data was really entered to my database. How do I view if it was entered? I'm a beginner so please try to use beginner SQL and VS vocabulary. I've tried going to show table data but that shows that no data was entered so I'm assuming its not working. Whenever I hit the button it just gives me no response so I'm not sure.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
namespace DBHotel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string connectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Nicholas Hoffs\\source\\repos\\DBHotel\\DBHotel\\Hotel.mdf;Integrated Security=True";
private void instBttn_Click(object sender, EventArgs e)
{
string nameQuery = textInst.Text;
using(SqlConnection conn = new SqlConnection(connectionString))
{
using(SqlCommand cmd = new SqlCommand(nameQuery, conn))
{
conn.Open();
cmd.CommandText = "INSERT INTO Customers(name) VALUES(#nameQuery)";
cmd.Parameters.AddWithValue("nameQuery", nameQuery);
cmd.ExecuteNonQuery();
}
}
}
}
}
Help is very much appreciated, thanks!
I know this is nonintuitive but try using the # inside your AddWithValue:
cmd.Parameters.AddWithValue("#nameQuery", nameQuery);
EDIT: WARNING The below solution is at risk of sql injection, and is highly discouraged.
As you are using direct query in instead of using stored procedure, you can't pass parameter to SQL. Instead of passing parameter try using
cmd.CommandText = "INSERT INTO Customers(name) VALUES('" + nameQuery + "')";
this means we are just concatenating the value of variable "nameQuery" in the query itself. so no need of below statement
cmd.Parameters.AddWithValue("nameQuery", nameQuery);
I am trying to simply insert values into an SQL table. The ID in the database cannot be AUTO_INCREMENT so I use MAX and +1. Not only will this code not make a new ID, it simply isn't inserting anything into the table.
Even in the debugger there are no errors or warnings, it just isn't showing up in the database itself..
Here is my code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Windows;
using System.ComponentModel;
using System.Drawing;
using System.Text;
namespace WebApplication2
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ButtonClick(object sender, EventArgs e){
using (var sqlConnection1 = new SqlConnection("Data
Source=SERVER; Initial Catalog = Metal; Integrated
Security = True"))
{
SqlDataAdapter cmd = new SqlDataAdapter();
using (var insertData = new SqlCommand("INSERT INTO ApptIn
(CONTROLNUMBER, CARRIERNAME, EXPECTEDNUMOFPIECES, EXPECTEDWEIGHT) VALUES
(#carrierSelectInput,
#pieceCountInput, #weightinput)")
{
SqlCommand generateApptNum = new SqlCommand();
View appNumView = new View();
insertData.Connection = sqlConnection1;
string carrierSelectInput = DropDownList1.Text;
string pieceCountInput = TextBox1.Text;
string weightInput = TextBox2.Text;
insertData.Parameters.Add("#carrierSelectInput",
carrierSelectInput.VarChar);
insertData.Parameters.Add("#pieceCountInput",
pieceCountInput.Int);
insertData.Parameters.Add("#weightInput",
weightInput.Int);
cmd.InsertCommand = insertData;
sqlConnection1.Open();
insertData.ExecuteNonQuery();
generateApptNum.ExecuteNonQuery();
sqlConnection1.Close();
}
}
}
}
}
EDIT: I have tried running the SQL into the DB and it gave an error, so I changed it(updated in code) but it puts in at ID=0...
I know you have already committed to your plan, but, I feel that I have to point out that, due to the sub select for the Max id value in your query, the insert statement has the potential to be much slower than a normal insert.
If you are planning on inserting a large number of rows or creating an API for use throughout the code I highly recommend either adjusting the column definition to be an identity column or to consider using a a sequence to generate the ids.
The issue could be that you need to specify the CommandType to be CommandType.Text on the insertData command. There is a lot going on in the original code with multiple sqlcommands being declared. I think the code could be simplified as such:
protected void ButtonClick(object sender, EventArgs e)
{
using (var sqlConnection1 = new SqlConnection("data source=testServer;initial catalog=testCat;integrated security=True;"))
using (var insertData = new SqlCommand("insert into tempExample (id, code, description) values ((select max(coalesce(id, 1)) from tempExample)+1, #code, #description)", sqlConnection1))
{
insertData.CommandType = CommandType.Text;
insertData.Parameters.AddWithValue("#code", "Testing4");
insertData.Parameters.AddWithValue("#description", "Testing3");
sqlConnection1.Open();
insertData.ExecuteNonQuery();
sqlConnection1.Close();
}
}
Update - I changed the code above to reflect a working test on my local machine. Note that the connection string format is different (lack of spaces).
Hey Members i am new to C# Language and Visual Studio Platform recently i am learning how to connect access Database with visual Studio and first time with same code i have connected with database but after some time when i compiled again then there is error given in Title.
why this is happening ?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Clinic_Management_System
{
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
private void Login_Load(object sender, EventArgs e)
{
try
{
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users
\Hassan Gillani\Documents\Clinic Management System.accdb; Persist Security Info = False; ";
connection.Open();
label1.Text = "Connected to Clinic Management System Database";
connection.Close();
}
catch (Exception exp)
{
MessageBox.Show("Error " + exp);
}
}
}
}
please visit given like to view screen short
http://s33.postimg.org/5ltm4dtnj/Error.png
Using the verbatim character (#) and splitting your path in the middle in not a good idea.
Spaces counts in paths so the filename used for your connection is
C:\Users \Hassan Gillani\Documents\Clinic Management System.accdb;
If you try to use File.Exists on this string you get false as result.
Do not split your connection string in the middle of the path
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\Hassan Gillani\Documents\Clinic Management System.accdb;
Persist Security Info = False; ";
i have a web server on internet i am using php/mysql. for my website, now i want to connect to my mysql database on my webserver using my c# windows form application so that i will be able to view,create, update, delete the data on mysql database on webserver, i want to user same database for website and my desktop application. i want any one having my desktop application would be able to update my database on my webserver(i mean not only form some specific ip).
Here is my code when i try to run it shows error "Unable to connect to any of specified MySQL hosts."
can any one Guide me how to do it. Thanks.
The following code is working fine for localhost but not working for web-server which is on internet.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient; // for mysql
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string con_str = "SERVER=fdb4.biz.nf;Port=3306;DATABASE=1558711_zee;UID=1558711_zee;PASSWORD=multan321;compress=true;";
MySqlConnection connection = new MySqlConnection(con_str);
try {
connection.Open();
MySqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM zeetable";
MySqlDataAdapter mda = new MySqlDataAdapter(cmd);
DataSet mds = new DataSet();
mda.Fill(mds);
dataGridView1.DataSource = mds.Tables[0].DefaultView;
}
catch(MySqlException ex){
MessageBox.Show(ex.Message);
}
}
}
}