C# SQL query exception - c#

I'm using C# in .NET 2.0 and I'm trying to access and manipulate a database. I can read as many times from the DB as I want and everything works, but as soon as I try to insert an item I get the following error message:
ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.
I've tried to look this up, but the fixes I was able to find either didn't work or weren't applicable.
I have the following code:
using (SqlConnection conn = new SqlConnection(SQLConnectionString))
{
SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT [Col1] FROM [Table1] WHERE [Col2]='" + val2 + "'", conn);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
if (dataSet.Tables.Count == 0 || dataSet.Tables[0].Rows.Count != 1)
{
SqlCommand cmd = new SqlCommand("INSERT INTO [Table1] ([Col1], [Col2]) VALUES ('" + val1 + "', '" + val2 + "')", conn);
cmd.ExecuteNonQuery();
}
}
Note: I'm sure I have permissions set up properly, since Visual Studio can insert with the same SQLConnectionString. Also, I am still fairly new to databases, so if I'm doing anything blantently wrong, please let me know.
Thanks.

The .Fill() opens the connection if it was not open and then closes it after it's done (only if it did open it itself). That's why that Fill did work. See MSDN.
But the .ExecuteNonQuery() doesn't do that, so you need to manually open the connection, with a
conn.Open();
either just before the ExecNonQuery or before the Fill.
As you are using a "using block", you don't need to explicitly Close() the connection, but that would not be wrong.

You don't appear to be opening the connection to perform your update (the exception tells you this).
Try this
SqlCommand cmd = new SqlCommand("INSERT INTO [Table1] ([Col1], [Col2]) VALUES ('" + val1 + "', '" + val2 + "')", conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
You can get more details and working example on MSDN at http://msdn.microsoft.com/en-us/library/sd2728ad.aspx

When you call dataAdapter.Fill(dataSet); it will automatically open and close connection.
So you need to reopen connection before using insert statement, or replace DataAdapter with SqlCommand and keep connection opened until you execute insert statement.

You didn't open the connection.
This page shows you how to open a SqlConnection with the using statement.
Your Friend the C# Using Statement

Call conn.Open() before calling cmd.ExecuteNonQuery().

You have to open connection, before executing command
conn.Open()
SqlCommand cmd = new SqlCommand("INSERT INTO [Table1] ([Col1], [Col2]) VALUES ('" + val1 + "', '" + val2 + "')", conn);
cmd.ExecuteNonQuery();
conn.Close()

You need to call con.open before you call con.ExecuteNonQuery and con.Close after it. Dataadapter.fill is doing it for you behind the scenes in the earlier code.

Check conn.IsOpen property before using cmd. And SqlCommand is disposable object too, its better practice to enclose it into "using" block.

No-one above is checking to make sure the connection opened.
I use this in my production code:
using (var conn = new SqlConnection(SQLConnectionString))
{
conn.Open();
if (conn.State == ConnectionState.Open)
{
SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT [Col1] FROM [Table1] WHERE [Col2]='" + val2 + "'", conn);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
if (dataSet.Tables.Count == 0 || dataSet.Tables[0].Rows.Count != 1)
{
SqlCommand cmd = new SqlCommand("INSERT INTO [Table1] ([Col1], [Col2]) VALUES ('" + val1 + "', '" + val2 + "')", conn);
cmd.ExecuteNonQuery();
}
}
}

Related

IN SQL Query Error ""Incorrect syntax near '0)'." in c#

SqlConnection con = new SqlConnection(#"Data Source=HAMMAD2-PC\SQLEXPRESS;Initial Catalog=StockManagement;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand(#"INSERT INTO [StockManagement].[dbo].[Product] ([ProductID], [ProductName], [SalePrice], [PurchasePrice], [Status])
VALUES ('" + pcodetxt.Text + "','" + pnametxt.Text + "','" + rtlpricetxt + "','" + purpricetxt.Text + "','" + statuscbox.SelectedIndex+")'",con);
cmd.ExecuteNonQuery();
con.Close();
This code causes an error
Incorrect syntax near '0)'
What is the solution?
I'm using Visual Studio 2012 and SQL Server
There wouldn't be such an error if you have used parameters, plus you would be protected from "SQL injection attack". ie:
using (SqlConnection con = new SqlConnection(#"server=.\SQLEXPRESS;Initial Catalog=StockManagement;Integrated Security=True"))
using (SqlCommand cmd = new SqlCommand(#"INSERT INTO [StockManagement].[dbo].[Product]
([ProductID]
,[ProductName]
,[SalePrice]
,[PurchasePrice]
,[Status])
VALUES
(#pid, #pname, #salePrice, #purPrice, #status)", con))
{
cmd.Parameters.Add("#pid", SqlDbType.Int).Value = int.Parse(pcodetxt.Text);
cmd.Parameters.Add("#pname", SqlDbType.VarChar).Value = pnametxt.Text;
cmd.Parameters.Add("#salePrice", SqlDbType.Money).Value = decimal.Parse(rtlpricetxt);
cmd.Parameters.Add("#purPrice", SqlDbType.Money).Value = decimal.Parse(purpricetxt.Text);
cmd.Parameters.Add("#status", SqlDbType.Int).Value = statuscbox.SelectedIndex;
con.Open();
cmd.ExecuteNonQuery();
con.Close(); // This is not needed: it is done by the implicit Dispose when exiting the using block
}
The error is because you're missing a closing quote in your sql statement, but you shouldnt be creating your statement manually with string manipulation in any case - this is very error prone, and extremely unsafe!
Use declared parameters instead.
See What's the best method to pass parameters to SQLCommand?
Incorrect Syntax near X, tries to show you that there is some thing wrong just before or after the X.
In your query you have placed ' in wrong place
So just rewrite it as below:
SqlCommand cmd = new SqlCommand(#"INSERT INTO [StockManagement].[dbo].[Product] ([ProductID], [ProductName], [SalePrice], [PurchasePrice], [Status])
VALUES ('" + pcodetxt.Text + "','" + pnametxt.Text + "','" + rtlpricetxt + "','" + purpricetxt.Text + "','" + statuscbox.SelectedIndex+"')",con);
Note: Using following code you put your self in the scope of the SQL Injection vulnerability, so you should always try to write the code as #CetinBasoz posted or other similar methods that makes you secure against the similar vulnerabilities.

Error connecting to MS Access database from C# Winform

I'm a student programmer and I'm writing this software for a small school, it's my first program, the code below is giving me the error
syntax error in insert into statement
I know the connection string is not the problem because I use it for inserting into two other tables with the same insert into format.
I am using an access database.
The offending code is
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "insert into studentBillRecords (StudentName, Department, Level, AccomodationStatus, SemesterBill, PreviousBalance, TotalBill) values ('"+ txtSRstudentName.Text + "', '" + cmbSRDepartment.Text + "', '" + cmbSRLevel.Text + "', '" + cmbSRAccomodationStatus.Text + "', '" + txtSRSemesterBill.Text + "', '" + txtSRPreviousBalance.Text + "', '" + txtSRTotalBill.Text + "')";
MessageBox.Show(command.CommandText);
command.ExecuteNonQuery();
connection.Close();
This same code with different table names, column names and input works with another table in the same database but won't work with this one.
Level is a reserved keyword in access.
Also use Parameters instead of concatinating string. Try this code out, it makes it safer and easier to read:
Note: I changed the name of the column Level to StudentLevel which, I assume, doesn't exist yet in your table.
try
{
using (OleDbConnection connection = new OleDbConnection("my connection string"))
{
//Open connection
connection.Open();
//Create new command
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;
//Create command text
cmd.CommandText =
"INSERT INTO studentBillRecords " +
"(StudentName, Department, StudentLevel, AccomodationStatus, SemesterBill, PreviousBalance, TotalBill) VALUES " +
"(#StudentName, #Department, #StudentLevel, #AccomodationStatus, #SemesterBill, #PreviousBalance, #TotalBill)";
// Add names paremeters
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#StudentName", txtSRstudentName.Text),
new OleDbParameter("#Department", cmbSRDepartment.Text),
new OleDbParameter("#StudentLevel", cmbSRLevel.Text),
new OleDbParameter("#AccomodationStatus", cmbSRAccomodationStatus.Text),
new OleDbParameter("#SemesterBill", txtSRSemesterBill.Text),
new OleDbParameter("#PreviousBalance", txtSRPreviousBalance.Text),
new OleDbParameter("#TotalBill", txtSRTotalBill.Text)
});
//Execute Query
cmd.ExecuteNonQuery();
//No need to close because we are using "using"
}
}
catch (OleDbException ex)
{
//If an exception occurs let's print it out to console
Console.WriteLine("ERROR: " + ex.ToString());
throw;
}
For information on how to change the column name read this:
https://msdn.microsoft.com/en-us/library/bb177883(v=office.12).aspx
"Level" is a keyword in MS Access, may be that is why this issue occurs try quoting it like [Level]
List Of MS Access Keywords

my insert command not changing the database when using through programming

When I am inserting values with query database is inserting when doing it with coding it won't insert although it show successful. Im using C# 2010 and 2012 Both are not adding
My Code
con.Open();
cmd = new SqlCommand("insert into Main_2(Name,NIC,NA_ID,PS_ID) values('" + name + "','" + nic + "',(SELECT NA_ID FROM NationalAssembly WHERE Name='" + na_name + "'),(SELECT PS_ID FROM ProvisionalAssembly Where Name='" + ps_name + "'))", con);
cmd = new SqlCommand("UPDATE ProvisionalAssembly SET Count=+1 WHERE Name='" + ps_name + "'", con);
cmd = new SqlCommand("UPDATE NationalAssembly SET Count=+1 WHERE Name='" + na_name + "'", con);
cmd.ExecuteNonQuery();
con.Close();
SqlCommand is a class, that means it is a reference types.
Everytime you create a new SqlCommand object and you assing it cmd as a reference. That means only your last SqlCommand executes. Your first two SqlCommand doesn't have a reference anymore in memory when you execute with ExecuteNonQuery method.
If you want to execute all these commands, you need to execute separately for each command.
And please use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your database connections.
using(SqlCommand cmd = new SqlCommand(YourInsertStatement))
{
con.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = YourFirstUpdateStatement;
cmd.ExecuteNonQuery();
cmd.CommandText = YourSecondUpdateStatement;
cmd.ExecuteNonQuery();
}

Database insert error: "string or binary data would be truncated"

When I log in, I am storing my username in the session. My requirement is that I want to store my username in my database. Here I am storing it in username1. When the username is entered, I can print it using response.write() and it is printing perfectly. However, when I am storing it in the database it is producing this error:
**sqlException was unhandled by user code
and exception at cmd.ExecuteScalar();
String or binary data would be truncated.
The statement has been terminated.**
Following is my ado.net code:
using (SqlConnection con =
new SqlConnection("Data Source=.;database=testdb1;Integrated Security=SSPI")) {
con.Open();
// SqlCommand cmd = new SqlCommand("delete from fileinfo where ID=" + Convert.ToInt32(Request.Params["one"]), con);
string uname = (string) Session["fname"].ToString() + " " + Session["lname"].ToString(); //Session["fname"].ToString()+" "+Session["lname"].ToString();
// Response.Write(uname);
// uname = "sri hari";
uname = uname + " ";
string uname1 = uname;
uname = uname.Trim();
SqlCommand cmd = new SqlCommand("insert into qry_details values('" + txt_query_name.Text + "','pending for approval','" + txt_query_description.Text + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "','" + qry + "','" + uname1 + "')", con);
cmd.ExecuteScalar();
}
check the length of qry_details table and see if its smaller than the string you send to the db?
basically the exception says you are trying to something bigger than the column length.
I would recommend you using a parametrized query. Your code is now vulnerable to SQL injection. Also you should use the ExecuteNonQuery method on the SQL command instead of ExecuteScalar when inserting values to the database:
var connectionString = "Data Source=.;database=testdb1;Integrated Security=SSPI";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "INSERT INTO qry_details VALUES (#query_name, 'pending for approval', #query_description, #date, #qry, #username)";
cmd.Parameters.AddWithValue("#query_name", txt_query_name.Text);
cmd.Parameters.AddWithValue("#query_description", txt_query_description.Text);
cmd.Parameters.AddWithValue("#date", DateTime.Now);
cmd.Parameters.AddWithValue("#qry", qry);
cmd.Parameters.AddWithValue("#username", uname1);
cmd.ExecuteNonQuery();
}
This error mostly happen when the inserting value is larger than the field width defined in table on SQL Server.
Check if you are inserting date and time using DateTime.Now c# fuction, your Table must be of type DateTime. not Date or Time only.

selecting data between 2 dates

I am Working in ASP.NET and SqlServer.
I have two textboxes with calender extender in my application where user will select two dates.I want to get data between those two dates from sqlserver where my datatype for that particular field is DateTime. please tell me how to proceed with this ...I wrote a query but thats not working..
my query:
SqlCommand cmd = new SqlCommand("select top 1 OrderNumber from tblOrderMaster where OrderedDate>='" + txtfromcal.Text + "' and OrderedDate<='" + txttocal.Text + "' ", conn);
things to do
parameterized the query to prevent from sql injection
use using statement to properly dispose the object
use try-catch block to handle excpetion
eg,
string query = #"select top 1 OrderNumber
from tblOrderMaster
where OrderedDate BETWEEN #startDate AND #endDate";
using(SqlConnection conn = new SqlConnection("connectionString here"))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#startDate", txtfromcal.Text);
cmd.Parameters.AddWithValue("#endDate", txttocal.Text);
try
{
conn.Open();
// other codes
// to fetch the record
}
catch(SqlException e)
{
// do something with
// e.ToString()
}
}
}
SOURCES
AddWithValue Method
Add (recommended method to be used)
use this code:
Sqlcommand cmd=new sql command ("Select data from tablename
where date>=startdate
and date<=enddate",connection)
Try this
SELECT * FROM YourTableName WHERE sqlDateColumnName BETWEEN '" + textbox1.Text + "' AND '" + textbox2.Text + "'

Categories

Resources