DataAdapter.UpdateCommand not working c#? - c#

I am using this code to update "SOME" columns in a table in my database. But everytime I try to do so an error is given.
No value given for one or more required parameters.
con.Open();
SlipDA = new OleDbDataAdapter();
string sqlUpdate = "Update tbl_Slip SET RaiseBasic=#RaiseBasic, OtherDed=#OtherDed, Arrears=#Arrears, Notes=#Notes WHERE SlipNo=#SlipNo";
SlipDA.UpdateCommand = new OleDbCommand(sqlUpdate, con);
SlipDA.UpdateCommand.Parameters.AddWithValue("#RaiseBasic", Convert.ToInt32(dRow[4].ToString()));
SlipDA.UpdateCommand.Parameters.AddWithValue("#OtherDed", Convert.ToInt32(dRow[5].ToString()));
SlipDA.UpdateCommand.Parameters.AddWithValue("#Arrears", Convert.ToInt32(dRow[7].ToString()));
SlipDA.UpdateCommand.Parameters.AddWithValue("#Notes", dRow[8].ToString());
SlipDA.UpdateCommand.Parameters.AddWithValue("#SlipNo", dRow[0].ToString());
SlipDA.UpdateCommand.ExecuteNonQuery();
con.Close();
The table contains 9 columns but I only want to update a few.

This Could be the problem :
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text. In this case, the
question mark (?) placeholder must be used. For example: SELECT * FROM
Customers WHERE CustomerID = ?
source : this
so basically your query should be like this :
string sqlUpdate = "Update tbl_Slip SET RaiseBasic= ?, OtherDed= ?, Arrears= ?, Notes= ? WHERE SlipNo= ?";

try this
string sqlUpdate = "Update tbl_Slip SET RaiseBasic=#RaiseBasic, OtherDed=#OtherDed, Arrears=#Arrears, Notes=#Notes WHERE SlipNo=#SlipNo";
OleDbCommand UpdateCommand = new OleDbCommand(sqlUpdate, con);
UpdateCommand.Parameters.AddWithValue("#RaiseBasic", Convert.ToInt32(dRow[4].ToString()));
UpdateCommand.Parameters.AddWithValue("#OtherDed", Convert.ToInt32(dRow[5].ToString()));
UpdateCommand.Parameters.AddWithValue("#Arrears", Convert.ToInt32(dRow[7].ToString()));
UpdateCommand.Parameters.AddWithValue("#Notes", dRow[8].ToString());
UpdateCommand.Parameters.AddWithValue("#SlipNo", dRow[0].ToString());
con.Open();
UpdateCommand.ExecuteNonQuery();
con.Close();

Related

insert value from TextBox into sql

I'm getting this error message: Cannot insert the value NULL into column 'id', table ''; column does not allow nulls. INSERT fails. thanks in advance
protected void AddItem(object sender, EventArgs e)
{
string insertCmd = "INSERT INTO Picture (Album, id) VALUES (#Album, #id)";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
// Create parameters for the SqlCommand object
// initialize with input-form field values
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
myCommand.Parameters.Add("#id", SqlDbType.Int).Direction = ParameterDirection.Output;
myCommand.ExecuteNonQuery();
int id = (int)myCommand.Parameters["#id"].Value;
}
}
I suppose that ID is an IDENTITY column. Its value is generated automatically by the database engine and you want to know what value has been assigned to your record.
Then you should change your query to
string insertCmd = #"INSERT INTO Picture (Album) VALUES (#Album);
SELECT SCOPE_IDENTITY()";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
int newID = Convert.ToInt32(myCommand.ExecuteScalar());
}
The query text now contains a second instruction SELECT SCOPE_IDENTITY() separated from the first command by a semicolon. SCOPE_IDENTITY returns the last IDENTITY value generated for you by the database engine in the current scope.
Now the command is run using the ExecuteScalar to get back the single value returned by the last statement present in the query text without using any output parameter
I would think that ID is identity. You don't have to add this value. I would try the following code and check the database if you get automatically an ID.
string insertCmd = "INSERT INTO Picture (Album) VALUES (#Album)";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
// Create parameters for the SqlCommand object
// initialize with input-form field values
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
myCommand.ExecuteNonQuery();
}
I case you want to set the id yourself(withoud automatic increment from the db), you should change the schema of the database removing identity from ID as shown below:
I hope this helps
If you need to stay this column empty you can try to replace to ' '(blank). This will work if you column is not "Key"
Or try to use:
substitute a value when a null value is encountered
NVL( string1, replace_with )
You can do this using stored procedure. Below is the script for Create stored procedure.
CREATE PROCEDURE [dbo].[InsertIntoPicture]
#Album varchar(500)=null,
#id int=0 output
AS
BEGIN
insert INTO Picture(Album)VALUES(#Album)
SET #id=##IDENTITY
END
Below is the code for call stored procedure with C# .
string insertCmd = "InsertIntoPicture";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
myCommand.Parameters.Add("#id", SqlDbType.Int).Direction = ParameterDirection.Output;
myCommand.ExecuteNonQuery();
int id = (int)myCommand.Parameters["#id"].Value;
}
Using above code you can insert a date from TextBox and also get last inserted record ID as an output variable as per your requirement.
Thanks .

How to update MySql table row through C# console application?

I am writing a console application and fetch data from MySql table .
Code :
string connection = "Server=localhoht;Database=data;Uid=root;Pwd=root123";
MySqlConnection dbcon = new MySqlConnection(connection);
MySqlCommand selectData;
dbcon.Open();
selectData = dbcon.CreateCommand();
selectData.CommandText = "SELECT user_id, user_name,user_type FROM win_user WHERE user_type=1 ORDER BY user_id ASC ";
MySqlDataReader juh = selectData.ExecuteReader();
And its working fine. Now I want to update a row with the code below :
string updatedata = "UPDATE win_user SET user_type='1' WHERE user_id= '1'";
MySqlDataAdapter MyData = new MySqlDataAdapter();
MyData.UpdateCommand = new MySqlCommand(updatedata, dbcon);
But its not working.
You can run the commend "UPDATE win_user SET user_type='1' WHERE user_id= '1'" in any sql client tools, eg, navicat, to verify wheather it's correct on your mysql database.
The MySqlDataAdapter could be used to update rows in a database table using the Update method.
The Update method (link is for SqlServer but the concept is the same) has many overload, but basically it requires a DataTable with rows modified in some way ([RowState != DataRowState.Unchanged][2]) so the MySqlDataAdapter can pick the rows changed and apply the DeleteCommand, UpdateCommand and InsertCommand defined in the adapter
Your code above doesn't shown any kind of interaction with a datatable and you have a call to the Update method so there is no way for the update to occur.
You could, of course execute directly your command without any adapter involved
EDITed to change every user_type not 1 to 1
string updatedata = "UPDATE win_user SET user_type=1 WHERE user_type <> 1";
MySqlCommand cmd = new MySqlCommand(updatedata, dbcon);
int numOfRowsChanged = cmd.ExecuteNonQuery();

why we use "#" while inserting or updating or deleting data in sql table

I just want to know why we use "#" while inserting or updating or deleting data in sql table, as I used #name like below.
cmd.Parameters.Add(new SqlParameter("#fname", txtfname.Text));
See: SqlParameter.ParameterName Property - MSDN
The ParameterName is specified in the form #paramname. You must
set ParameterName before executing a SqlCommand that relies on
parameters.
# is used by the SqlCommand so that the value of the parameter can be differentiatd in the Command Text
SqlCommand cmd = new SqlCommand("Select * from yourTable where ID = #ID", conn);
^^^^^^^
//This identifies the parameter
If # is not provided with the parameter name then it is added. Look at the following source code, (taken from here)
internal string ParameterNameFixed {
get {
string parameterName = ParameterName;
if ((0 < parameterName.Length) && ('#' != parameterName[0])) {
parameterName = "#" + parameterName;
}
Debug.Assert(parameterName.Length <= TdsEnums.MAX_PARAMETER_NAME_LENGTH, "parameter name too long");
return parameterName;
}
}
EDIT:
If you don't use # sign with the parameter then consider the following case.
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
conn.Open();
cmd.CommandText = "SELECT * from yourTable WHERE ID = ID";
cmd.Connection = conn;
cmd.Parameters.AddWithValue("ID", 1);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
}
The above will fetch all the records, since this will translate into SELECT * from yourTable WHERE 1=1, If you use # above for the parameter ID, you will get only the records against ID =1
OK, no offense to the posters before me but I will try to explain it to you as simple as possible, so even a 7 year old understands it. :)
From my experience '#' in .SQL is used when you are "just not making it clear what exact data type or exact name will be used". "Later" you are pointing out what the exact value of '#' is.
Like, say, someone has developed some huge .SQL query which contains, say, the name of every person who has received it.
SELECT column_name,column_name FROM table_name WHERE column_name = #YOURNAME;
#YOURNAME = 'John Doe';
So, in this case, it's easier for everyone to just write their name at #YOURNAME and it will automatically convert the query to (upon launch):
SELECT column_name,column_name FROM table_name WHERE column_name = 'John Doe';
P.S: I am sorry for my syntax errors and incorrect terminology but I am sure you should have understood it by now. :)
Variables and parameters in SQL Server are preceded by the # character.
Example:
create procedure Something
#Id int,
#Name varchar(100)
as
...
When you create parameter objects in the C# code to communicate with the database, you also specify parameter names with the # character.
(There is an undocumented feature in the SqlParameter object, which adds the # to the parameter name if you don't specify it.)

OleDbDataAdapter Update To dbf [Free Table] -Syntax Error()

When I insert through the OleDbCommand with direct values no problem, it's working fine
OleDbCommand OleCmd1 = new OleDbCommand("Insert into My_Diary (sl_no,reminder) values("+a1+",'CHECK VALUE')", OleCon1);
OleCmd1->ExecuteNonQuery();
But when I like to update through parameter its showing "Syntax Error"....I can't identify my mistake...
string MyConStr = "Provider=VFPOLEDB.1; Data Source='C:\\For_Dbf'; Persist Security Info=False";
InsSavDiaryCmd = "Insert into My_Table1 (sl_no,reminder) values (#sl_no,#reminder) ";
VFPDAp=gcnew OleDbDataAdapter();
VFPDApMy_Table1InsertCommand = gcnew OleDbCommand(InsSavDiaryCmd, OleCon1);
WithInsVar = VFPDAp.InsertCommand.Parameters;
WithInsVar.Add("#sl_no", OleDbType.Integer, 10, "sl_no");
WithInsVar.Add("#reminder", OleDbType.Char, 250, "reminder");
OleCon1.ConnectionString = MyConStr;
OleCon1.Open();
OleDbTransaction Trans=OleCon1.BeginTransaction();
//VFPDAp.DeleteCommand.Transaction = Trans;
//VFPDAp.UpdateCommand.Transaction = Trans;
VFPDAp.InsertCommand.Transaction = Trans;
VFPDAp.Update(MyDataTbl);
Trans.Commit();
OleCon1.Close();
The OleDbCommand doesn't use named parameters. You need to change the insert statement so that it uses questions.
InsSavDiaryCmd = "Insert into My_Table1 (sl_no,reminder) values (?, ?) ";
You need to make sure that you have a parameter for each question mark and make sure that the parameters are inserted in order of their use in the insert statement.
** If you'd like to use name parameters... you can try using VfpClient which is a project that I'm working on to make data access a little nicer from .Net.

how do i update data in access database using c# 2010

OleDbConnection vcon = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\SummerJob\DataBase.accdb");
string cmdtxt = "UPDATE Students SET S_Name = ?, S_Surname = ?, S_E-Mail = ? WHERE ID = ?";
OleDbCommand cmd = new OleDbCommand(cmdtxt, vcon);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("S_Name", EditName.Text);
cmd.Parameters.AddWithValue("S_Surname", editSurname.Text);
cmd.Parameters.AddWithValue("S_E-Mail", editMail.Text);
vcon.Open();
cmd.ExecuteNonQuery();
vcon.Close();
//i use this code but it says syntax error in update statement
Where is the last parameter ???
ID=?
Not sure, but I will bet that without that parameter your query doesn't look right to the parser.
You need to pass ID? via SqlParameter like this cmd.Parameters.AddWithValue("ID", Id.Text);
Also make sure that the parameters are added in the same order they occur

Categories