I have some trouble to update my sql server 2005 database when i use parameters.Here you can see the code that normally has to work.I precise that i already make others treatments such as insert into and it worked perfectly.
myCommand.Parameters.AddWithValue("#Pk", this.pk);
myCommand.Parameters.AddWithValue("#Titre", this.titre);
myCommand.CommandText = "Update Action set titre=#Titre where pk=#Pk";
//Execute la commande
myCommand.ExecuteNonQuery();
EDIT:When i use hard code such as:
myCommand.CommandText = "Update Action set titre='title' where pk=#Pk";
it works...
I don't know where you went wrong this is the working code for me
string strCon = #"Data Source=SYSTEM19\SQLEXPRESS;Initial Catalog=TransactionDB;Integrated Security=True";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection cn = new SqlConnection(strCon);
SqlCommand cmd = new SqlCommand("select * from tblTransaction1", cn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
txtName.Text = ds.Tables[0].Rows[i]["FirstName"].ToString();
txtName1.Text = ds.Tables[0].Rows[i]["LastName"].ToString();
}
}
}
Button click code
protected void btnInsert_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(strCon);
obj1.FirstName = txtName.Text;
obj1.LastName = txtName1.Text;
if (obj1.upDate(cn))
{
}
}
Sample class code file
private bool m_flag = false;
private string strFirstName;
private string strLastName;
public string FirstName
{
get { return strFirstName; }
set { strFirstName = value; }
}
public string LastName
{
get { return strLastName; }
set { strLastName = value; }
}
public bool upDate(SqlConnection con)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
if (con.State != ConnectionState.Open)
{
con.Open();
}
try
{
cmd.Parameters.AddWithValue("#Fname", FirstName);
cmd.Parameters.AddWithValue("#Lname", LastName);
cmd.CommandText = "Update tblTransaction1 set LastName=#Lname where FirstName=#Fname";
if (cmd.ExecuteNonQuery() > 0)
{
m_flag = true;
}
}
catch
{
}
return m_flag;
}
Sample Images
I've seen weird results when you forget to include the "CommandType" parameter. Since you using inline SQL, it should be set to "CommandType.Text".
myCommand.Parameters.AddWithValue("#Pk", this.pk);
myCommand.Parameters.AddWithValue("#Titre", this.titre);
myCommand.CommandText = "Update Action set titre=#Titre where pk=#Pk";
// Added CommandType //
myCommand.CommandType = CommandType.Text;
//Execute la commande
myCommand.ExecuteNonQuery();
I have noticed that copying the entire code into a new project helps. I have ran into many times my code would work and then the next day would not, or would only work for someone else and not me. Usually this is due to the designer side of the project when adding and removing code from your project. Just because you delete specific code does not mean the program can update the entire class/project.
If you do :
Int32 rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
What does it say ?
Try also to prefix your Action table, with the schema name, for example :
myCommand.CommandText = "Update MySchema.Action set titre=#Titre where pk=#Pk";
Because sometimes it can depend on the schema and the user's rights to update this schema.
You could try this: instead of adding the parameters like that
myCommand.Parameters.AddWithValue("#Titre", this.titre);
you should add them with data type.
myCommand.Parameters.Add(new SqlParameter("#Titre", SqlDbType.VarChar, 50));
myCommand.Parameters["#Titre"].Value = this.titre;
That way, the final SQL will be Update Action set titre='titre' instead of Update Action set titre=title. Look that in the second statement titre is not inside quotes ''.
Try adding the parameters after declaring the command.
myCommand.CommandText = "Update Action set titre=#Titre where pk=#Pk";
myCommand.Parameters.AddWithValue("#Pk", this.pk);
myCommand.Parameters.AddWithValue("#Titre", this.titre);
//Execute la commande
myCommand.ExecuteNonQuery();
I found something similar (not identical) here: http://forums.asp.net/t/1249831.aspx/1
Related
I have the following code:
SqlCommand writeCommand = new SqlCommand("INSERT INTO computers(id)VALUES()", conn.GetConnection());
writeCommand.ExecuteNonQuery();
The table computers contains an INT idientity(1,1) column named id.
When I run the code, I get a System.Data.SqlClient.SqlException: Incorrect syntax near ')'. I've tried to find a solution, but can't find one on the internet.
If the table has other columns as well, and you want to populate them with NULL or their DEFAULT values, then you can use DEFAULT VALUES:
INSERT INTO dbo.computers
DEFAULT VALUES;
If, however, your table only have the one column, then personally using an IDENTITY is the wrong choice; a table that just has an IDENTITY is clearly being misused. Instead, use a SEQUENCE:
CREATE SEQUENCE dbo.Computers START WITH 1 INCREMENT BY 1;
This scales far better, and doesn't suffer the likely race conditions you have. Then, when running an INSERT (or similar) you would use NEXT VALUE FOR dbo.Computers.
For an auto-incrementing identity column the database handles the id value unless I missed something in what you are attempting to do.
public void DemoInsert(string ComputerName, ref int newIdentifier)
{
using (var conn = new SqlConnection { ConnectionString = ConnectionString })
{
using (var cmd = new SqlCommand { Connection = conn })
{
cmd.CommandText = "INSERT INTO computers (ComputerName) " +
"VALUES (#ComputerName); " +
"SELECT CAST(scope_identity() AS int);";
cmd.Parameters.AddWithValue("#ComputerName", ComputerName);
cn.Open();
newIdentifier = (int)cmd.ExecuteScalar();
}
}
}
I have similar code like your app, think about it simple crud app
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con;
SqlDataAdapter da;
SqlCommand cmd;
DataSet ds;
void fillGrid()
{
con = new SqlConnection("Data Source=.;Initial Catalog=schoolDb;Integrated Security=True");
da = new SqlDataAdapter("Select * from ogrenciler",con);
ds = new DataSet();
con.Open();
da.Fill(ds, "students");
dataGridView1.DataSource = ds.Tables["students"];
con.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
fillGrid();
}
private void Addbtn_Click(object sender, EventArgs e)
{
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText="insert into students(StudentId,StudentName,StudentSurname,City) values("+StudentId.Text+",'"+StudentName.Text+"','"+StudentSurname.Text+"','"+City.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
fillGrid();
}
private void Updatebtn_Click(object sender, EventArgs e)
{
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "update Students set ogrenci_ad='"+StudentName.Text+"',StudentName='"+StudentSurname.Text+"',City='"+City.Text+"' where StudentId="+StudentId.Text+"";
cmd.ExecuteNonQuery();
con.Close();
fillGrid();
}
private void Deletebtn_Click(object sender, EventArgs e)
{
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "delete from ogrenciler where ogrenci_no="+StudentId.Text+"";
cmd.ExecuteNonQuery();
con.Close();
fillGrid();
}
}
}
I'm pretty sure that the Sql Syntax is right since it's a legit query.
However i've never stumbled on this issue before.
private void button1_Click(object sender, EventArgs e)
{
string ett = textBox1.Text;
if (ett == "")
{
MessageBox.Show("Du måste fylla i UID, vilket du finner i användarlistan.");
return;
}
try
{
if (connect.State == ConnectionState.Open)
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandText = "DELETE FROM Users WHERE uid = #uid";
cmd.Parameters.AddWithValue("#uid", textBox1.Text);
MySqlDataReader accessed = cmd.ExecuteReader();
MessageBox.Show("Användaren borttagen.");
}
else
{
MessageBox.Show("Något gick tyvärr fel, kontakta systemadministratören.");
}
}
catch (Exception ex)
{
{ MessageBox.Show(ex.Message); }
}
}
The problem may be related to this:
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandText = "DELETE FROM Users WHERE uid = #uid";
cmd.Parameters.AddWithValue("#uid", textBox1.Text);
MySqlDataReader accessed = cmd.ExecuteReader();
MessageBox.Show("Användaren borttagen.");
}
try
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandType = CommandType.Text
cmd.CommandText = "DELETE FROM Users WHERE uid = #uid";
cmd.Parameters.AddWithValue("#uid", textBox1.Text);
cmd.ExecuteNonQuery
MessageBox.Show("Användaren borttagen.");
}
Now you've shown us your whole code in the comments, the problem is obvious.
You have written a method to initialise, set up and open your database connection; and this other method which runs on a button click, which uses it.
However, nowhere in your code do you call the method which initialises your database connection, therefore it is not set up when you try to use it - obvious really.
I can see you think you are checking to see if the connection is working by checking its State property, but calling any sort of method or property accessor on an uninitialised reference type won't work, you'll get the NullReferenceException you've been getting.
To fix, call the connection set up method from your button press, before trying to use the connection:
private void button1_Click(object sender, EventArgs e)
{
string ett = textBox1.Text;
if (ett == "")
{
MessageBox.Show("Du måste fylla i UID, vilket du finner i användarlistan.");
return;
}
try
{
db_connection(); //added this line
if (connect.State == ConnectionState.Open)
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandText = "DELETE FROM Users WHERE uid = #uid";
cmd.Parameters.AddWithValue("#uid", textBox1.Text);
MySqlDataReader accessed = cmd.ExecuteReader();
MessageBox.Show("Användaren borttagen.");
}
else
{
MessageBox.Show("Något gick tyvärr fel, kontakta systemadministratören.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You have not defined the variable, "connect".
Changes are not saved to the SQL database
Why would I want to use '#' in the sql statement instead of the way that I have the statement?
Code:
private void button_Save_Customer_Click(object sender, EventArgs e)
{
sqlString = Properties.Settings.Default.ConnectionString;
SqlConnection sqlConnection = new SqlConnection(sqlString);
try
{
string customer_Ship_ID = customer_Ship_IDTextBox.ToString();
string customer_Ship_Address = customer_Ship_AddressTextBox.Text;
SQL = "UPDATE Customer_Ship SET Customer_Ship_Address = customer_Ship_Address WHERE Customer_Ship_ID = customer_Ship_ID";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.AddWithValue("Customer_Ship_ID", customer_Ship_ID);
sqlCommand.Parameters.AddWithValue("Customer_Ship_Address", customer_Ship_Address);
sqlCommand.CommandText = SQL;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
MessageBox.Show("Record Updated");
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
Here you can check the MSDN reference for the update command.
Use parameters, Why?
Also check that you need to open and close the connection object, not the command.
In case you want to update the rows with the Customer_ID = "something" you could do like this:
The code (updated after your changes):
private void button_Save_Customer_Click(object sender, EventArgs e)
{
string sqlString = Properties.Settings.Default.ConnectionString;
SqlConnection sqlConnection = new SqlConnection(sqlString);
try
{
int customer_Ship_ID;
if(int.TryParse(customer_Ship_IDTextBox.Text, out customer_Ship_ID))
{
string customer_Ship_Address = customer_Ship_AddressTextBox.Text;
// Customer_Ship: Database's table
// Customer_Ship_Address, Customer_Ship_ID: fields of your table in database
// #Customer_Ship_Address, #Customer_Ship_ID: parameters of the sqlcommand
// customer_Ship_ID, customer_Ship_Address: values of the parameters
string SQL = "UPDATE Customer_Ship SET Customer_Ship_Address = #Customer_Ship_Address WHERE Customer_Ship_ID = #Customer_Ship_ID";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.AddWithValue("Customer_Ship_ID", customer_Ship_ID);
sqlCommand.Parameters.AddWithValue("Customer_Ship_Address", customer_Ship_Address);
sqlCommand.CommandText = SQL;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
MessageBox.Show("Record Updated");
}
else
{
// The id of the textbox is not an integer...
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
Seems like your syntax isn't correct. Here's the syntax for the Update:
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
So, Update, what to set, and WHERE to set (which you seem to be missing).
For more, have a look here.
Check your update query
Change it like
string SQL = string.format("UPDATE Customer_Ship SET Customer_Ship_Address='{0}'",putUrVaue);
I have a class which I have written all my methods there.
then I have my firstpage of web application which I have some codes there.
I face this
$exception {"Fill: SelectCommand.Connection property has not been initialized."} System.Exception {System.InvalidOperationException}
in the line :
sda.Fill(dsUsers.tblMembers);
here is my code so I hope u can help me:
namespace MosquesNetwork
{
public class cUsers2
{
SqlConnection scn;
SqlDataAdapter sda;
SqlCommandBuilder scb;
SqlCommand SqlStr;
public cUsers2()
{
SqlConnection scn = new SqlConnection (ConfigurationManager.ConnectionStrings["MosquesDBConnectionString"].ConnectionString);
sda = new SqlDataAdapter();
scb = new SqlCommandBuilder(sda);
}
public bool CheckUserName(string UserName)
{
DsUsers2 dsUsers=new DsUsers2();
bool Success;
string SqlStr="select * from tblUsers where Username='"+UserName+"' ";
sda.SelectCommand=new SqlCommand(SqlStr, scn);
sda.Fill(dsUsers.tblMembers);
sda.Fill(dsUsers.tblMembers);
Success=dsUsers.tblMembers.Rows.Count>0;
return Success;
}
then I have this code while the login button is pressed in webform:
protected void Button1_Click(object sender, EventArgs e)
{
if (txtuser.Text.Trim().Length>0 && txtpass.Value.Length>0 )
{
cUsers2 cUsers=new cUsers2();
DsUsers2 dsUser=new DsUsers2();
bool Success;
if (txtuser.Text.Trim()=="admin")
{
Success=cUsers.CheckAdminPass(txtuser.Text.Trim(),txtpass.Value.Trim());
if (Success)
{
Response.Redirect("WebForm2.aspx");
}
}
dsUser=cUsers.Checkpassword(txtuser.Text.Trim(), txtpass.Value.Trim(),out Success);
if(Success)
{
Session["ID"]=dsUser.tblMembers.Rows[0][dsUser.tblMembers.IDUserColumn].ToString();
System.Web.HttpContext.Current.Response.Redirect("frmProfile.aspx");
}
else lblerror.Text="invalid username & password";
}
}
Look at your constructor:
SqlConnection scn = new SqlConnection(...);
That's declaring a separate scn local variable, so the scn instance variable is staying as null. If you just change it to:
scn = new SqlConnection(...);
that may well fix the immediate problem. It's not a nice design in my view - I'd prefer to create the SqlConnection in a using block where you actually need it - but that's what's going wrong for now...
I got also this problem. after search the problem found that the object of connection that i have provide SqlDataAdapter is not Initialize so the connection passed as null
Vishal Sir, If You are Getting that Problem then Be sure whether you are passing the 'cmd' to the SQL DATA ADAPTER.
for eg:
ad = new SqlDataAdapter(cmd);
//Try To Fetch The Value Like this...
protected void Search_Emp_Click(object sender, EventArgs e)
{
SqlCommand cmd;
SqlConnection con;
SqlDataAdapter ad;
con = new SqlConnection(); //making instance of SqlConnection
con.ConnectionString = ConfigurationManager.ConnectionStrings["cn"].ConnectionString; //Invoking Connection String
con.Open(); //Opening Connection
if (Ddl_Emp_Search.SelectedItem.Text == "Date Of Joining")
{
cmd = new SqlCommand("Select Emp_Name,Contact_No,City,Emp_Desig,Place_Code from emp_registration where Emp_Doj=#Emp_Doj",con);
cmd.Parameters.Add("#Emp_Doj", SqlDbType.NVarChar, 50).Value = TextBox1.Text;
}
else if (Ddl_Emp_Search.SelectedItem.Text == "Name")
{
cmd = new SqlCommand("Select Emp_Name,Place_Code,Emp_Code,Emp_Desig from emp_registration where Emp_Name=#Emp_Name", con);
cmd.Parameters.Add("#Emp_Name", SqlDbType.NVarChar, 50).Value = TextBox1.Text;
}
else if (Ddl_Emp_Search.SelectedItem.Text == "Employee Code")
{
cmd = new SqlCommand("Select Emp_Name,Contact_No,City,Emp_Desig,Place_Code from emp_registration where Emp_Code=#Emp_Code", con);
cmd.Parameters.Add("#Emp_Code", SqlDbType.NVarChar, 50).Value = TextBox1.Text;
}
else if (Ddl_Emp_Search.SelectedItem.Text == "City")
{
cmd = new SqlCommand("Select Emp_Name,Contact_No,City,Emp_Desig,Place_Code from emp_registration where City=#City", con);
cmd.Parameters.Add("#City", SqlDbType.NVarChar, 50).Value = TextBox1.Text;
}
else
{
Response.Write("There is Something Worng....");
}
ad = new SqlDataAdapter(cmd); // Here IS THE PROBLEM WHEN YOU DOES'NT PASS CMD (Command instance) to the Data Adapter then there is a problem of ( Fill: SelectCommand.Connection property has not been initialized)
DataSet ds = new DataSet();
ad.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
I want to Check the "refno" already present in Tbldelivery table, If "refno" is present, then it will insert in "Tbldeliverydetails" because "refno" is primary key in 1st table. Where i check the condition ?
Here is the code i wrote in C# :
protected void btndlysave_Click(object sender, EventArgs e)
{
SqlConnection SqlCon = new SqlConnection("server=(local);Initial Catalog=TestDB;Integrated Security=SSPI;");
try
{
SqlCon.Open();
SqlCommand cmd = new SqlCommand("insert into Tbldelivery (refno,deliverdate,requestby,projectcode) values
(#refno,#deliverdate,#requestby,#projectcode) WHERE not exists (select refno from Tblinkdelivery where refno = #refno)", SqlCon);
cmd.CommandType = CommandType.Text;
if ( need check here)
cmd.Parameters.AddWithValue("#refno", txtdelrefno.Text.Trim());
cmd.Parameters.AddWithValue("#deliverdate", txtdeldate.Text.Trim());
cmd.Parameters.AddWithValue("#requestby", txtdelreq.Text.Trim());
cmd.Parameters.AddWithValue("#projectcode", ddlprojcode.Text.Trim());
}
else
{
SqlCommand cmd2 = new SqlCommand("insert into Tbldeliverdetails (refno,printercode,inkcode,quantity,price,notes) values (#refno,#printercode,#inkcode,#quantity,#price,#notes)", SqlCon);
cmd2.CommandType = CommandType.Text;
cmd2.Parameters.AddWithValue("#refno", txtdelrefno.Text.Trim());
cmd2.Parameters.AddWithValue("#printercode", ddldelprcode.Text.Trim());
cmd2.Parameters.AddWithValue("#inkcode", ddlinkcode.Text.Trim());
cmd2.Parameters.AddWithValue("#quantity", txtdelqty.Text.Trim());
cmd2.Parameters.AddWithValue("#price", txtdelprice.Text.Trim());
cmd2.Parameters.AddWithValue("#notes", txtdelnotes.Text.Trim());
int val1 = cmd.ExecuteNonQuery();
int val2 = cmd2.ExecuteNonQuery();
}
finally
{
SqlCon.Close();
}
}
I think first of all you need to arrange your code.
Writing everything inside the button click event is not good at all. It is better if you can separate business logic and put it separately.
Try something like this.
You can create Data Access class which handle your data access.
In your Data Access Class
public SqlConnection OpenConnection()
{
try
{
var conn = new SqlConnection(“xxx”);
conn.Open();
return conn;
}
catch (Exception ex)
{
//log the exception
return null;
}
}
YourFunction(parameters)
{
var conn = OpenConnection();
if(conn != null)
{
//your code
// you can do something similar as JeremyK explained here
}
}
And in your button click
protected void btndlysave_Click(object sender, EventArgs e)
{
//CHECK THE PARAMETERS AND PASS
//DataAccess. YourFunction(parameters)
}
You query the table and see if it exists.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand sqlCommand =
new SqlCommand("SELECT * FROM dbo.Tbldelivery WHERE refno=#refno",
connection);
sqlCommand.Parameters.Add("#refno", System.Data.SqlDbType.VarChar);
sqlCommand.Parameters["#refno"].Value = refnoValue;
SqlDataReader reader = sqlCommand.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
// refno exists
}
else
{
// refno does not exist
}
}