Problems with Executing a DB2 External Stored Procedure - c#

I am trying to call an external stored procedure (calls an RPG program). I keep getting the following error:
"Exception Details: IBM.Data.DB2.iSeries.iDB2SQLErrorException: SQL0104 Token #SSN was not valid. Valid tokens: :."
Here is my code:
using (iDB2Connection conn = new iDB2Connection(_CONNSTRING))
{
conn.Open();
string sqlStatement = "MPRLIB.SIGNTIMESHEET (#SSN, #SIGNATURE, #WORKSTATION, #TOTALHOURS, #COMMENT)";
//string sqlStatement = "MPRLIB.SIGNTIMESHEET (?, ?, ?, ?, ?)";
iDB2Command cmd = conn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = sqlStatement;
cmd.Parameters.Add("#SSN", timesheet.EmployeeUniqueKey.ToString("0000000000"));
cmd.Parameters.Add("#SIGNATURE", timesheet.EmployeeTypedName);
cmd.Parameters.Add("#WORKSTATION", timesheet.EmployeeSignedComputer);
cmd.Parameters.Add("#TOTALHOURS", GetJobHoursTotal(timesheet.Id).ToString("00000.000").Replace(".", ""));
cmd.Parameters.Add("#COMMENT", timesheet.EmployeeComments);
cmd.ExecuteNonQuery();
conn.Close();
}
I can't seem to figure out what is happening or why I am getting the above error. My connection string looks like:
private const string _CONNSTRING = "DataSource=192.168.50.200;DefaultCollection=QMFILES;Naming=sql;UserID=XXX;Password=XXX;";
Could it be a library list issue? The program just references one file that is in the library list. Any suggestions?

Try like this:
using (var conn = new iDB2Connection(_CONNSTRING))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "MPRLIB.SIGNTIMESHEET";
cmd.Parameters.Add("#SSN", timesheet.EmployeeUniqueKey.ToString("0000000000"));
cmd.Parameters.Add("#SIGNATURE", timesheet.EmployeeTypedName);
cmd.Parameters.Add("#WORKSTATION", timesheet.EmployeeSignedComputer);
cmd.Parameters.Add("#TOTALHOURS", GetJobHoursTotal(timesheet.Id).ToString("00000.000").Replace(".", ""));
cmd.Parameters.Add("#COMMENT", timesheet.EmployeeComments);
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?

Issue in update statement

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();
}

Incrementing an int during insert

I'm trying to increment an integer in an MS Access table from a c# .net page during insert.
I'm getting a syntax error when attempting the following. Also unsure if I should be using an ExecuteNonQuery() or not?
OleDbCommand cmd = new OleDbCommand("INSERT INTO tblTarget(target,ref) VALUES(#target,(SELECT MAX(ref)+1 FROM tblTarget)", conn);
cmd.Parameters.AddWithValue("#target", TextTitle.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
You miss a bracket after tblTarget:
OleDbCommand cmd =
new OleDbCommand("INSERT INTO tblTarget(target,ref) VALUES(#target,(SELECT MAX(ref)+1 FROM tblTarget))", conn);
Here is a little review of your code, try using the using pattern:
using(var conn = new Connection())
{
conn.Open();
string sql = "INSERT INTO tblTarget(target,ref) VALUES(#target,(SELECT MAX(ref)+1 FROM tblTarget))";
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.Parameters.AddWithValue("#target", TextTitle.Text);
cmd.ExecuteNonQuery();
}
You're missing a bracket, try:
INSERT INTO tblTarget(target,ref) VALUES(#target,(SELECT MAX(ref)+1 FROM tblTarget))
But I think you are going to have other issues, you need something closer to this:
INSERT INTO tblTarget ( target, ref )
SELECT #target AS Targ, First((SELECT MAX(ref)+1 FROM tblTarget)) AS MaxRef
FROM tblTarget
GROUP BY #target;
The correct way to achieve your goal is
string sql = "INSERT INTO tblTarget (target,ref) " +
"SELECT ?, MAX(ref)+1 FROM tblTarget";
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.Parameters.AddWithValue("#target", TextTitle.Text);
cmd.ExecuteNonQuery();
I would not do the increment by the sql or code, we can use AutoNumber data type for auto increase the value in access.
string sql = "INSERT INTO tblTarget(target) VALUES(#target)";
using(var conn = new Connection())
using(OleDbCommand cmd = new OleDbCommand(sql, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#target", TextTitle.Text);
cmd.ExecuteNonQuery();
}

"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.

Getting ORA-01036 error when using output parameter in C#

I am having a problem with an Output parameter in C#/Oracle. I have isolated the code that I need to get working.
This is part of a much larger SQL statement, so do not worry too much if it doesn't make sense. In short I need to copy a row, give it a new ID and return that new ID. I tried using "RETURNING" which did not work. I see no reason why the code below should not work, but I'm getting an "ORA-01036: illegal variable name/number" error. Can anyone see what I'm doing wrong?
using (OracleConnection conn = new OracleConnection(connString))
{
// Open connection and create command.
conn.Open();
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("outValue", OracleType.Int32).Direction = ParameterDirection.Output;
cmd.CommandText = "SELECT seq.nextval INTO :outValue FROM dual";
try
{
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
// This is just to see the exception when it fails.
}
}
}
The name of the parameter doesn't match.
cmd.Parameters.Add(":outValue", OracleType.Int32).Direction.......;
^
I have also seen this variation on the query syntax
"BEGIN SELECT seq.nextval INTO :outValue FROM dual END;"
You are using named parameters. Try setting:
cmd.BindByName = true;
Have you tried 'returning' keyword like this?
This code works for me.
using (OracleConnection conn = new OracleConnection(connString))
{
// Open connection and create command.
conn.Open();
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("outValue", OracleType.Int32).Direction = ParameterDirection.Output;
cmd.CommandText = "insert into table (id, value) values (seq.nextval, 'value') returning id into :outValue";
cmd.ExecuteNonQuery();
}
}

Categories