"Incorrect syntax" error when running SQL query [closed] - c#

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am trying to insert into database using this class, I am able to access this class in My Customer page, but getting error
Incorrect syntax near '#ZipCode'.
Meanwhile I don't have any stored procedure or trigger in my SQL Server database.
public class CustomerDLL
{
SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter da;
DataSet ds;
public CustomerDLL()
{
cn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
}
public void Insert_Customer(string name, string address, string city, string state, int ZipCode)
{
cmd = new SqlCommand("Insert into Customer values (#name, #address, #city, #state, #ZipCode", cn);
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#address", address);
cmd.Parameters.AddWithValue("#city", city);
cmd.Parameters.AddWithValue("#state", state);
cmd.Parameters.AddWithValue("#ZipCode", Convert.ToInt32(ZipCode) ); // Line 34
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
I am accessing this class in Customer page using this method
protected void btnAdd_Click(object sender, EventArgs e)
{
// Create an instance of CustomerDll
CustomerDLL cusdll = new CustomerDLL();
//int zip = Convert.ToInt32(txtZip.Text);
cusdll.Insert_Customer
(
txtName.Text,
txtAddress.Text,
txtCity.Text,
txtState.Text,
Convert.ToInt32(txtZip.Text)
);
lblMsg.Text = "Rec is inserted successfully";
cusdll = null;
}
I keep getting error
Incorrect syntax near '#ZipCode' on line 34.

I think you missed closing parenthesis after #ZipCode.

Related

C# | Login doesn't work [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I can't figure it out why my Login system doesn't work.
It always resulting "FALSE" or "WRONG PASSWORD" tho I've entered the right password.
And yes, I've checked the column name and the table name as well. Nothing wrong but doesn't work.
I can't figure it out.
namespace GitGut {
public partial class Login : Window {
public String thisName;
private String thisConnectionString = #"Data Source = THISISMINE\SQLEXPRESS;Initial Catalog = GitGut; Integrated Security = True";
public Login() {
InitializeComponent();
}
private void Button_Login_Click(object sender, RoutedEventArgs e) {
Console.WriteLine("Button_Login pressed.");
if(theValidation(TextBox_Username.Text, PasswordBox_Password.Password) == true) {
Dashboard Form_Dashboard = new Dashboard();
Form_Dashboard.Show();
this.Hide();
} else {
MessageBox.Show("ERROR", "ERROR");
}
}
private Boolean theValidation(String thisUsername, String thisPassword) {
SqlConnection thisSqlConnection = new SqlConnection(thisConnectionString);
SqlCommand thisSqlCommand = new SqlCommand();
thisSqlCommand.Parameters.Add("#Username", SqlDbType.VarChar).Value = thisUsername;
thisSqlCommand.Parameters.Add("#Password", SqlDbType.VarChar).Value = thisPassword;
String thisQuery = "SELECT * FROM [User] WHERE [Username] = '#Username' AND [Password] = '#Password'";
thisSqlCommand.Connection = thisSqlConnection;
thisSqlCommand.CommandText = thisQuery;
thisSqlConnection.Open();
SqlDataReader thisSqlDataReader = thisSqlCommand.ExecuteReader();
if(thisSqlDataReader.Read()) {
thisSqlConnection.Close();
return true;
} else {
thisSqlConnection.Close();
return false;
}
}
}
}
You should remove the ' from the query string:
String thisQuery = "SELECT * FROM [User] WHERE [Username] = #Username AND [Password] = #Password";
The Sqlcommand parameters does not need any separator/indicator. You are already telling what type they are in thisSqlCommand.Parameters.Add("#Password", SqlDbType.VarChar)..., so the query string is correctly constructed.

c# "ExecuteNonQuery requires an open and available Connection. The connection's current state is closed." [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
hello i have a problem with getting exception of "ExecuteNonQuery requires an open and available Connection. The connection's current state is closed."
public void AddCustomer(Customer customer)
{
string connectionString = #"Data Source=LIRON-PC\SQLEXPRESS;Initial Catalog=C:\Program Files\Microsoft SQL Server\MSSQL12.SQLEXPRESS\MSSQL\DATA\MatokMmagnet.mdf;Integrated Security=True";
using (m_sqlConnection = new SqlConnection(connectionString))
{
m_cmd = new SqlCommand();
m_cmd.CommandType = CommandType.Text;
m_cmd.Connection = m_sqlConnection;
m_cmd.Parameters.AddWithValue("#id", customer.id);
m_cmd.Parameters.AddWithValue("#FirstName", customer.FirstName);
m_cmd.Parameters.AddWithValue("#LastName", customer.LastName);
m_cmd.Parameters.AddWithValue("#Password", customer.Password);
m_cmd.CommandText = "INSERT INTO Customers (id, FirstName, LastName, Password)VALUES (#id, #FirstName, #LastName, #Password)";
try
{
m_cmd.ExecuteNonQuery();
}
catch(Exception e)
{
Console.WriteLine( e.Message);
}
finally
{
m_sqlConnection.Close();
}
}
}
Like the error says you must open the connection before executing the query like this :
public void AddCustomer(Customer customer)
{
string connectionString = #"Data Source=LIRON-PC\SQLEXPRESS;Initial Catalog=C:\Program Files\Microsoft SQL Server\MSSQL12.SQLEXPRESS\MSSQL\DATA\MatokMmagnet.mdf;Integrated Security=True";
using (m_sqlConnection = new SqlConnection(connectionString))
{`
m_sqlConnection.open();
//....
}
}

Strange C# error while inserting in database [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have 2 forms in my program. I am using a SQL Server Compact 3.5 database file (.sdf) from C#
albums_tbl table has two columns: id, name
In form 1 when I use this code :
private void button1_Click(object sender, EventArgs e)
{
SqlCeCommand cm = new SqlCeCommand("INSERT INTO albums_tbl(album_name) VALUES (#album_name) ", cn);
cm.Parameters.AddWithValue("#album_name", textBox1.Text);
int affectedrows = cm.ExecuteNonQuery();
if (affectedrows > 0)
{
MessageBox.Show("insert shod !");
}
}
the program inserts well, but when I use the exact code in form 2 it errors this when I want to insert :
You don't open connection yet.
SqlCeConnection conn = null;
try
{
conn = new SqlCeConnection("Data Source = MyDatabase.sdf; Password ='<pwd>'");
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO Customers ([Customer ID], [Company Name]) Values('NWIND', 'Northwind Traders')";
cmd.ExecuteNonQuery();
}
finally
{
conn.Close();
}
Refer: https://msdn.microsoft.com/en-us/library/system.data.sqlserverce.sqlceconnection(v=vs.100).aspx
Hope this helps.
You have not opened a connection , you just simply need to do as follow
private void button1_Click(object sender, EventArgs e)
{
SqlCeConnection con=new SqlCnConnection("Data Source = MyDatabase.sdf; Password ='<pwd>'");
SqlCeCommand cm = new SqlCeCommand("INSERT INTO albums_tbl(album_name) VALUES (#album_name) ", cn);
cm.Parameters.Add(new SqlCeParameter(#album_name, textBox1.Text));
con.Open();
cm.ExecuteNonQuery();
}

Login Form using sql database c# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to make a sign up page . you put user name and password and its save in the sql database.
note: evrey thing worked until i add the 2nd column(the password).
this is the password code(the username is the same) :
static public void delete(string _Password)
{
try
{
connection.Open();
SqlCeCommand commandInsert = new SqlCeCommand("INSERT INTO [Table] VALUES(#Password)", connection);
commandInsert.Parameters.Add("Password", _Password);
commandInsert.ExecuteNonQuery();
}
catch (SqlCeException expection)
{
MessageBox.Show(expection.ToString());
}
finally
{
connection.Close();
}
}
And this is the button settings :
private void button1_Click(object sender, EventArgs e)
{
if (deleteBox.Text != "")
{
SQLFunctions.Insert(insertBox.Text);
SQLFunctions.delete(deleteBox.Text);
SQLFunctions.Refresh(this.dataGridView1);
}
else
{
MessageBox.Show("login failed");
}
}
thanks
I guess you need to modify your code little bit like this
SqlCeCommand commandInsert = new SqlCeCommand("INSERT INTO [Table] VALUES(#username,#Password)", connection);
you should pass two parameters as you have two fields in db now and if you don't want to pass username then you should specify this thing like this
SqlCeCommand commandInsert = new SqlCeCommand("INSERT INTO [Table](password) VALUES(#Password)", connection);
and also
commandInsert.Parameters.Add("Password", _Password);
this should be written as follows
commandInsert.Parameters.Add("#Password", _Password);
and to pass values to this parameter, you can do it like this
command.Parameters.AddWithValue("#Password", insertBox.Text);

Data not get inserted in Access database [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am developing a C# Windows application. I have used access database. When I selecting data from database I am getting data, but when inserting data it's not gets inserted and also it's not showing any error.
But when I run the same insert query in Access it gets inserted. Here is my code:
public void connCheck()
{
try
{
cn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database\MyDatabase.mdb;Persist Security Info=True;Jet OLEDB:Database Password=2013");
if (cn.State == ConnectionState.Closed)
cn.Open();
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
}
public bool ExecuteNonQuery()
{
try
{
connCheck();
string sqlQuery = "INSERT INTO tblResult(ExamSet,SetId,FullMarks,ObtainedMarks,MarksPercentage,ElapsedTime,LastQIndex,CreatedDate,Completed)
Values(1,27,'200.00',0,0,0,1,DATE(),'N')";
cmd.CommandType = CommandType.Text;
cmd.Connection = cn;
cmd.CommandText = sqlQuery;
cmd.ExecuteNonQuery();
return true;
}
catch(OleDbException ex)
{
ErrorMsg = ex.ToString();
return false;
}
finally
{
cn.Close();
cn.Dispose();
cmd.Dispose();
}
}
You did not defined your cmd..
add this line
OledbCommand cmd=new OledbCommand();
How about replacing your query code like this
string sqlQuery = "INSERT INTO tblResult([ExamSet],[SetId],[FullMarks],[ObtainedMarks],[MarksPercentage],[ElapsedTime],[LastQIndex],[CreatedDate],[Completed])
Values(1,27,'200.00',0,0,0,1,DATE(),'N')";
Update:
One of the issues could be Security warning that disables the content.
Try and see if this works (Go to your MDB):
Click on 'External Data' tab
There should be a Security Warning that states "Certain content in the database has been disabled"
Click the 'Options' button
Select 'Enable this content' and click the OK button
Try parameterised queries via cmd.Parameters.Add or AddRange. Example
var cmd = new SqlCommand("INSERT INTO tbl_name (a, b, c) VALUES (#a, #b, #c)");
cmd.Parameters.AddRange(new[] { new SqlParameter("#a", field1), new SqlParameter("#b", field2), new SqlParameter("#c", field2) });
(Posted on behalf of the OP).
Thanks everyone for your help, I got the solution. Actually there is no problem in my code. Problem is that I have created database file in a folder. But when I build the project it created a duplicate database with same folder an file name in bin folder.
So every time it gets inserted in that database. And I was checking in the database file which I have created. So I thought it's not working.

Categories

Resources