Strange C# error while inserting in database [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 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();
}

Related

cant update into the all column [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 6 years ago.
Improve this question
The c# code:
protected void check_click(object sender, EventArgs e)
{
SqlConnection c;
string str = "Data Source =(LocalDB)\\MSSQLLocalDB;";
str += "AttachDbFilename=|DataDirectory|\\DinoData.mdf;";
str += "Integrated Security= True";
c = new SqlConnection(str);
if (Page.IsValid)
{
Session["tit"] = (string)title.Text;
Session["Discrip"] = (string)Discrip.Text;
Session["Doname"] = (string)Dinoname.Text;
Session["wage"] = (string)wage.Text;
Session["lo"] = (string)ddlcountry.SelectedItem.Text;
Session["val"] = (bool)true;
Response.Redirect("Had Manger.aspx", true);
SqlCommand zer = new SqlCommand("UPDATE [User] SET did4 = 0", c);
c.Open();
zer.ExecuteNonQuery();
c.Close();
}
}
there is not an error but it is not updating
plss help
ok i update ehis is all the function
You are calling Response.Redirect("Had Manger.aspx", true); before you even hit your query execute. Comment that line out or move it to the end and you should be ok.
Response.Redirect("Had Manger.aspx", true);

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();
//....
}
}

"Incorrect syntax" error when running SQL query [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 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.

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