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();
}
Related
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.
I am trying to populate 11 textboxes, using my database information.
private void button5_Click(object sender, EventArgs e)
{
SqlConnection CN = new SqlConnection();
CN.ConnectionString = cons;
try
{
CN.Open();
SqlCommand cmd = new SqlCommand("SELECT FROM Lista1 WHERE DescripcionNombre = "
' + comboBox1.text + '
"",
CN)
;
SqlDataReader myReader = cmd.ExecuteReader();
}
catch
{
MessageBox.Show("You failed!");
}
}
It always fails, not even able to get that right....
The error is in this line of code
SqlCommand cmd = new SqlCommand("SELECT FROM Lista1 WHERE DescripcionNombre = "' + comboBox1.text + '"", CN);
It should be either like this
SqlCommand cmd = new SqlCommand("SELECT * FROM Lista1 WHERE DescripcionNombre = '" + comboBox1.text + """, CN);
Or
SqlCommand cmd = new SqlCommand("SELECT Column1_name, column2_name FROM Lista1 WHERE DescripcionNombre = '" + comboBox1.text + "'", CN);
As you have not selected any columns it didn't work as you expected.
And in the side note pass paramater value instead of passing the value straight from the field values. so that you can avoid SQL Injection
SqlCommand cmd = new SqlCommand("SELECT Column1_name, column2_name FROM Lista1 WHERE DescripcionNombre = #DescripcionNombre", CN);
cmd.Parameters.AddWithValue("#DescripcionNombre", comboBox1.text);
The first order of business would be to write this line properly:
SqlCommand cmd = new SqlCommand("SELECT FROM Lista1 WHERE DescripcionNombre = "' + comboBox1.text + '"", CN);
That's not valid SQL or C#. You need to specify which columns to retrieve from the table. If want all columns then use a wildcard. The next order of business is to learn how to concatenate strings. If you want single quotes to be part of the string literal then they have to be inside the double quotes.
SqlCommand cmd = new SqlCommand("SELECT * FROM Lista1 WHERE DescripcionNombre = '" + comboBox1.text + "'", CN);
That's quite elementary stuff. You should spend some time reading a tutorial or two.
Once that's done, you then need to actually read the data from the data reader. This can help with that. Note the use of parameters rather than string concatenation in those examples? You can learn more about that here.
SqlCommand cmd = new SqlCommand("SELECT FROM Lista1 WHERE DescripcionNombre = "' + comboBox1.text + '"", CN);
You are not selecting any columns or expressions in your SELECT
Your single and double quotes are backwards in the concatenation
You should get in the habit of using parameters instead of concatenating SQL (for several reasons, not the least of which is SQL Injection vulnerability)
A valid statement would be:
SqlCommand cmd = new SqlCommand("SELECT * FROM Lista1 WHERE DescripcionNombre = '"
+ comboBox1.text
+ "'", CN);
You forget to mention column name which you need to fetch in query
Always use parameterized queries How does SQLParameter prevent SQL Injection
SqlCommand cmd = new SqlCommand("SELECT * FROM Lista1 WHERE DescripcionNombre=#DescripcionNombre, CN);
cmd.Parameters.AddWithValue("#DescripcionNombre", comboBox1.text);
But your query should be like this
SqlCommand cmd = new SqlCommand("SELECT * FROM Lista1 WHERE DescripcionNombre = '" + comboBox1.text + "'", CN);
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.
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 + "'
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();
}
}
}