Issue in update statement - c#

I am writing the following lines of code to update the data in access database.
using (OleDbConnection con = new OleDbConnection())
{
con.ConnectionString = String.Format(Queries.dbConnection, databasePath);
con.Open();
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText = "update tblusers set password = #password where userId = #userId;";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("#userId", authResult.UserId);
cmd.Parameters.AddWithValue("#password", newPassword);
cmd.ExecuteNonQuery();
}
}
When this line runs cmd.ExecuteNonQuery(); I got the following error:
Syntax error in UPDATE statement
Am I missing anything?
Update - 2
using (OleDbConnection con = new OleDbConnection())
{
con.ConnectionString = String.Format(Queries.dbConnection, databasePath);
con.Open();
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText = "update tblusers set password = ? where userId = ?;";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add("p1", OleDbType.VarChar, 100).Value = newPassword;
cmd.Parameters.Add("p2", OleDbType.Integer).Value = authResult.UserId;
cmd.ExecuteNonQuery();
}
}

First of all: MS Access / OleDB does not used named parameters - but positional parameters. So the order in which you specify the parameters is very much relevant!
Second: OleDB uses the ? as a parameter placeholder.
So try this code:
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText = "update tblusers set [password] = ? where userId = ?;";
cmd.CommandType = System.Data.CommandType.Text;
// parameters - do *NOT* use "AddWithValue", and specify in the *correct order*!
// since the parameters are *positional*, the name provided is irrelevant
cmd.Parameters.Add("p1", OleDbType.VarChar, 50).Value = newPassword;
cmd.Parameters.Add("p2", OleDbType.Integer).Value = authResult.UserId;
cmd.ExecuteNonQuery();
}

Related

md5 password query check through c#

Database query in SQL Server side.
declare #password varchar(100) = '12345aA!'
select user_id, username from tblusers
where password=CONVERT(NVARCHAR(32),HashBytes('MD5', #password), 2);
This query works fine and below is the output. It gives one record, ok?
Below is C# code to validate password
var query = "select user_id from tblusers";
query += " where password=CONVERT(NVARCHAR(32), HashBytes('MD5', #password), 2);";
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = _config.GetConnectionString("backend");
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#password", form.password);
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
//not entering in this scope
}
}
}
}
Due to some reasons c# code is unable to validate password through sql query. Am I missing anything?

Executing Oracle procedure

I connected my oracle database to visual studio and now I'm trying to execute procedure I created in my database.
I tried this:
OracleCommand cmd = new OracleCommand("BEGIN ADD_USER('"+txtName.Text+"','"+txtName2.Text+"',"+txtID.Text+"); END;" );
cmd.ExecuteNonQuery();
My procedure has 3 parameters : name, 2name, id. It works fine when I use this command in sqldeveloper, but I get error when I try it in my project.
using (OracleConnection cn = new OracleConnection("con string"))
{
cn.Open();
OracleCommand cmd = new OracleCommand("ADD_USER");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = cn;
cmd.Parameters.Add("YourSPParamName1", OracleDbType.{YourFieldTypeInDB}).Value = txtName.Text;
cmd.Parameters.Add("YourSPParamName2", OracleDbType.{YourFieldTypeInDB}).Value = txtName2.Text;
cmd.Parameters.Add("YourSPParamName3", OracleDbType.{YourFieldTypeInDB}).Value = txtID.Text;
cmd.ExecuteNonQuery();
}
Something like this should work.
Here's how It works for me:
OracleConnectionStringBuilder sb = new OracleConnectionStringBuilder();
sb.DataSource = "localhost";
sb.UserID = "something";
sb.Password = "pass";
OracleConnection conn = new OracleConnection(sb.ToString());
conn.Open();
OracleCommand cmd = new OracleCommand("ADD_USER");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
cmd.Parameters.Add("NAME", OracleDbType.Varchar2).Value = txtName.Text;
cmd.Parameters.Add("NAME2", OracleDbType.Varchar2).Value = txtName2.Text;
cmd.Parameters.Add("ID", OracleDbType.Int32).Value = txtID.Text;
cmd.ExecuteNonQuery();

Inserting data to multiple table in my sqlworkbench

I'm a new coder trying to code C# to insert data into sqlworkbench database. Having alot of problems. Looking for any help. Thanks.
private void enterbutton_Click(object sender, EventArgs e)
{
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=;database=mydb;";
conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("insert into garden(idGarden) VALUES (#idGarden)");
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#idGarden", gardentextBox.Text);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
SqlCommand cmd1 = new SqlCommand("insert into rainfall(aveRainfall) VALUES (#aveRainfall)");
cmd1.Connection = conn;
cmd1.Parameters.AddWithValue("#aveRainfall", aveRaintextBox.Text);
cmd1.ExecuteNonQuery();
cmd1.Parameters.Clear();
SqlCommand cmd2 = new SqlCommand("insert into seat(idSeat) VALUES (#idSeat)");
cmd2.Connection = conn;
cmd2.Parameters.AddWithValue("#idSeat", seatIDtextBox.Text);
cmd2.ExecuteNonQuery();
cmd2.Parameters.Clear();
SqlCommand cmd3 = new SqlCommand("insert into temperature(currentTemp) VALUES (#currentTemp)");
cmd3.Connection = conn;
cmd3.Parameters.AddWithValue("#currentTemp", currentTemptextBox.Text);
cmd3.ExecuteNonQuery();
cmd3.Parameters.Clear();
conn.Close();
}
You didn't connect your SqlCommand's with your MySqlConnection. And I think they should MySQLSqlCommand instead of SqlCommand.
You can assing their .Connection properties to your MySqlConnection. Like;
cmd.Connection = conn;
cmd2.Connection = conn;
cmd3.Connection = conn;
cmd4.Connection = conn;
And you try to execute your cmd only. I think you should execute your all others commands like cmd2, cmd3 and cmd4..
cmd.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
cmd3.ExecuteNonQuery();
cmd4.ExecuteNonQuery();
And could be better to use using statement to dispose your database connections..
using(MySqlConnection conn = new MySqlConnection(myConnectionString))
using(MySQLCommand cmd = conn.CreateCommand())
{
//
}
Also always prefer to use Add() instead of AddWithValue().
Read: http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/

"executenonquery connection property has not been initialized"

SqlConnection cn = new SqlConnection(#"DataSource=dbedu.cs.vsb.cz\SQLDB;Persist Security Info=True;User ID=*****;Password=*******");
SqlCommand cmd = new SqlCommand();
string finish = DropDownListFi.SelectedValue;
cn.Open();
String Name = Request.QueryString["Name"];
cmd.CommandText = "UPDATE navaznost_ukolu SET finish=#finish where Name='" + Name + "'";
cmd.Parameters.Add(new SqlParameter("#finish", finish));
cmd.ExecuteNonQuery();
cmd.Clone();
The error message
Executenonquery connection property has not been initialized.
the problem with your current code is that you have not set the Connection property of the SqlCommand object. Try this,
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
and you must also parameterized the values set on the name
String Name = Request.QueryString["Name"];
cmd.CommandText = "UPDATE navaznost_ukolu SET finish=#finish where Name=#name";
cmd.Parameters.Add(new SqlParameter("#finish", finish));
cmd.Parameters.Add(new SqlParameter("#name", Name));
FULL CODE
string finish = DropDownListFi.SelectedValue;
String Name = Request.QueryString["Name"];
string connStr = #"DataSource=dbedu.cs.vsb.cz\SQLDB;
Persist Security Info=True;
User ID=*****;
Password=*******";
string sqlStatement = #"UPDATE navaznost_ukolu
SET finish = #finish
WHERE Name = #Name";
using (SqlConnection conn = new SqlConnection(connStr))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = sqlStatement;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("#finish", finish));
cmd.Parameters.Add(new SqlParameter("#name", Name));
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch(SqlException e)
{
// do something with the exception
// do not hide it
// e.Message.ToString()
}
}
}
For proper coding
use using statement for propr object disposal
use try-catch block to properly handle objects
The error is self-explanatory, you have not assigned the connection to the command. You can use the constructor:
using(var cn = new SqlConnection(#"DataSource=dbedu.cs.vsb.cz\SQLDB;Persist Security Info=True;User ID=*****;Password=*******"))
using(var cmd = new SqlCommand(
"UPDATE navaznost_ukolu SET finish=#finish where Name=#Name"
, cn))
{
string finish = DropDownListFi.SelectedValue;
cn.Open();
String Name = Request.QueryString["Name"];
cmd.Parameters.AddWithValue("#finish", finish);
cmd.Parameters.AddWithValue("#Name", Name);
cmd.ExecuteNonQuery();
}
Note that i've also used a sql-parameter for the Name and using statements to ensure that anything implementing IDisposable gets disposed, even in case of an exception. This will also close the connection.

Call stored procedure and cursor parameter with OleDb

I'm developing an application in C# that connects to an Oracle 10g database.
I'm using Oledb like this:
OleDbConnection conn = ConnectionUtil.CreateConexion();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = SP_AUTENTICAR_USUARIO;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("p_SED_USUARIO", OleDbType.VarChar).Value = strUsuario;
cmd.Parameters.Add("p_SED_PASS", OleDbType.VarChar).Value = strPass;
cmd.Parameters.Add("p_cursor", OleDbType.Cursor).Direction = ParameterDirection.Output;//I dont know what to put here
conn.Open();
cmd.ExecuteNonQuery();
OleDbDataReader objReader = (OleDbDataReader)cmd.Parameters["p_cursor"].Value;
if (objReader.Read())
{...
I need to call a stored procedure and read a cursor with OleDbDataReader.
Any idea how to do that?
Thanks,
Please Check this sample code.this is using OracleDataReader
oraConn.Open();
OracleCommand cursCmd = new OracleCommand("CURSPKG.OPEN_TWO_CURSORS", oraConn);
cursCmd.CommandType = CommandType.StoredProcedure;
cursCmd.Parameters.Add("EMPCURSOR", OracleType.Cursor).Direction = ParameterDirection.Output;
cursCmd.Parameters.Add("DEPTCURSOR", OracleType.Cursor).Direction = ParameterDirection.Output;
OracleDataReader rdr = cursCmd.ExecuteReader();
Console.WriteLine("\nEmp ID\tName");
while (rdr.Read())
Console.WriteLine("{0}\t{1}, {2}", rdr.GetOracleNumber(0), rdr.GetString(1), rdr.GetString(2));
rdr.NextResult();
Console.WriteLine("\nDept ID\tName");
while (rdr.Read())
Console.WriteLine("{0}\t{1}", rdr.GetOracleNumber(0), rdr.GetString(1));
rdr.Close();
oraConn.Close();

Categories