return sql query with parameter - c#

I want to return my sql query with parameters assigned, but I can't. Can you explain how I can return the parameters as defined?
public string InsertText(string Ad, string Soyad, string OkulNo, int RolId, string TelNo)
{
string query = "INSERT INTO kutuphane.kisiler (Adi,Soyadi,No,RolId,TelNo) VALUES (#Adi,#Soyadi,#No,#RolId,#TelNo)";
MySqlCommand command = new MySqlCommand(query);
command.Parameters.Add("#Adi", MySqlDbType.VarChar).Value = Ad;
command.Parameters.Add("#Soyadi", MySqlDbType.VarChar).Value = Soyad;
command.Parameters.Add("#OkulNo", MySqlDbType.VarChar).Value = OkulNo;
command.Parameters.Add("#RolId", MySqlDbType.Int32).Value = RolId;
command.Parameters.Add("#TelNo", MySqlDbType.VarChar).Value = TelNo;
return command.CommandText;
}

You cannot. A parameterized query is more than just a string. If you are expecting to see the parameters replaced in the query: that's not what parameters are. I'd probably just return command here, and have the caller execute it (after setting the connection). Or just execute it inside the method and never have the query leave.

I'm not sure about my answer...
but have you tried to do this?
public MySqlCommand InsertText(string Ad, string Soyad, string OkulNo, int RolId, string TelNo)
{
string query = "INSERT INTO kutuphane.kisiler (Adi,Soyadi,No,RolId,TelNo) VALUES (#Adi,#Soyadi,#No,#RolId,#TelNo)";
MySqlCommand command = new MySqlCommand(query);
command.Parameters.Add("#Adi", MySqlDbType.VarChar).Value = Ad;
command.Parameters.Add("#Soyadi", MySqlDbType.VarChar).Value = Soyad;
command.Parameters.Add("#OkulNo", MySqlDbType.VarChar).Value = OkulNo;
command.Parameters.Add("#RolId", MySqlDbType.Int32).Value = RolId;
command.Parameters.Add("#TelNo", MySqlDbType.VarChar).Value = TelNo;
return command;
}
You can have MySqlCommand return directly instead of the string.
Remember that later you have to print the query in string format, as you did previously

Related

Editing data into SQL with C#

I have this method for Editing data but I don't know how to write the code... Until now I have this which I don't really understand and I have an error in it. It says incorrect syntax near '('.
public void EditMember(Member member)
{
string Name = member.Name;
string Surname = member.Surname;
string EntryDate = member.EntryDate.ToString("dd.MM.yyyy");
string Status = member.Status;
sqlConnection.Open();
sqlCommand = new SqlCommand(
"UPDATE Members SET (Name, Surname, EntryDate) VALUES('" + Name + "','" + Surname + "','" + EntryDate + "')' WHERE'(' Id '='" + member.Id + "')",
sqlConnection);
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
}
The problem is when I start to write WHERE
Help please.
Please read all of this answer, not just the first part
There are multiple issues here. The most immediate problem is here:
"')' WHERE'('
That's acting as if you're trying to quote the bracket. That "should" be:
"') WHERE ('
At that point it would look like a valid (but bad) INSERT command... but your use of VALUES which doesn't look like it's a valid way of updating in T-SQL anyway.
However, you shouldn't use this approach at all. It's error-prone, hard to read, and most importantly prone to SQL injection attacks.
Instead, you should use parameterized SQL:
string sql = #"UPDATE Members
SET Name = #Name, Surname = #Surname, EntryDate = #EntryDate
WHERE Id = #Id";
using (var connection = new SqlConnection(...))
{
connection.Open();
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#Name", SqlDbType.NVarChar).Value = member.Name;
command.Parameters.Add("#Surname", SqlDbType.NVarChar).Value = member.Surname;
command.Parameters.Add("#EntryDate", SqlDbType.DateTime).Value = member.EntryDate;
command.Parameters.Add("#Id", SqlDbType.NVarChar).Value = member.Id;
int rows = command.ExecuteNonQuery();
// TODO: Work out what to do if rows isn't 1
}
}
(With adjustments for the appropriate data types, of course.)
You should NEVER EVER concatenate together your SQL statements with user input.
Instead : use parametrized queries - they're easy to use, avoid SQL injection, and improve performance.
Try code something like this:
string updateStmt = "UPDATE dbo.Members SET Name = #Name, Surname = #Surname, EntryDate = #EntryDate WHERE Id = #ID";
sqlCommand = new SqlCommand(updateStmt, sqlConnection);
sqlCommand.Parameters.Add("#Name", SqlDbType.VarChar, 100).Value = name;
sqlCommand.Parameters.Add("#Surname", SqlDbType.VarChar, 100).Value = surname;
sqlCommand.Parameters.Add("#EntryDate", SqlDbType.DateTime).Value = entrydate;
sqlCommand.Parameters.Add("#ID", SqlDbType.Int).Value = member.Id;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
The correct syntax for an update statement is
"UPDATE Members SET Name = #name, Surname = #surname, EntryDate = #date WHERE id=#id"
Said that, you should use parameterized query like this
public void EditMember(Member member)
{
string Name = member.Name;
string Surname = member.Surname;
string EntryDate = member.EntryDate.ToString("dd.MM.yyyy");
string Status = member.Status;
sqlConnection.Open();
sqlCommand = new SqlCommand("UPDATE Members SET Name = #name, Surname = #surname, " +
"EntryDate = #date " +
"WHERE Id = #id", sqlConnection);
sqlCommand.Parameters.AddWithValue("#name", Name);
sqlCommand.Parameters.AddWithValue("#surname", Surname);
sqlCommand.Parameters.AddWithValue("#date", EntryDate);
sqlCommand.Parameters.AddWithValue("#id", Status);
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
As a side note, keep in mind that AddWithValue is a simple way to add parameters to you query, but if the perfomance of this query is critical it is better to use a fully defined parameter with the datatype that matches exactly your database column's type and with the exact size.
Remove the quotes from around the WHERE and you should be fine. Please heed the warnings given in the comments about SQL injection attacks.
Your code has syntax error for update and also SQLInjection issue.
You need to pass parameters to update query rather than passing direct values.
It should be as follows:
public void EditMember(Member member)
{
string Name = member.Name;
string Surname = member.Surname;
string EntryDate = member.EntryDate.ToString("dd.MM.yyyy");
string Status = member.Status;
sqlConnection.Open();
sqlCommand = new SqlCommand("UPDATE Members SET Name=#Name, Surname=#Sirname, EntryDate=#EntryDate WHERE Id = #id", sqlConnection);
sqlCommand.parameters.AddparameterWithValue("#Name",Name);
sqlCommand.parameters.AddparameterWithValue("#Surname",Surname);
sqlCommand.parameters.AddparameterWithValue("#EntryDate",EntryDate);
sqlCommand.parameters.AddparameterWithValue("#Id",Id);
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
}
Edit the post to make correct answer:
i.e. you don't need brackets in where clause. And yes the better query is
"UPDATE Members SET Name=#Name, Surname=#Surname, EntryDate=#EntryDate WHERE Id=#ID"
and then you add #Name, #Surname, .. etc through parameter of command object.

How to apply National Character set to dynamic query

I am trying to apply N before variable name for Unicode as mentioned in How to use 'LIKE' statement with unicode strings?
With the following code I am getting following error. What need to be corrected here?
Exception: Invalid column name 'N#input'.
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE N#input ";
CODE
static void Main(string[] args)
{
string result = DisplayTest("Daily Tax Updates: ----------------- Transactions");
}
private static string DisplayTest(string searchValue)
{
string test = String.Empty;
string connectionString = "Data Source=.;Initial Catalog=LibraryReservationSystem;Integrated Security=True;Connect Timeout=30";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE N#input ";
using (SqlCommand command = new SqlCommand(commandText, connection))
{
command.CommandType = System.Data.CommandType.Text;
command.Parameters.AddWithValue("#input", "%" + searchValue + "%");
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
test = reader.GetString(0);
}
}
}
}
}
return test;
}
I see a few issues.
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE N#input";
should be
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE #input";
...
command.Parameters.Add("#input",System.Data.SqlDbType.NVarChar,<<size>>);
command.Parameters[0].Value = "%" + searchValue + "%";
I see you're trying to use a nvarchar parameter. I think .net does that by default with .AddWithValue
I'm not sure why do you need the typecast to nvarchar, you should be fine without the 'N' part.
That part you need when you want to specify that a string literal should be treated as nvarchar not as varchar, as in SELECT * from Table where field like N'%VALUE%'
Otherwise, you just declare your variable/parameter as nvarchar
Taken from this stack Stack overflow
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "#CategoryName";
parameter.SqlDbType = SqlDbType.NVarChar;
parameter.Direction = ParameterDirection.Input;
parameter.Value = categoryName;
Try this one -
private static string DisplayTest(string searchValue)
{
string connectionString = "Data Source=.;Initial Catalog=LibraryReservationSystem;Integrated Security=True;Connect Timeout=30";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string commandText = #"SELECT AccountType,* FROM Account WHERE AccountType LIKE #input";
using (SqlCommand command = new SqlCommand(commandText, connection))
{
command.CommandType = System.Data.CommandType.Text;
command.Parameters.Add("#input", SqlDbType.NVarChar);
command.Parameters["#input"].Value = string.Format("%{0}%", searchValue);
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
return reader.GetString(0);
}
}
}
}
}
return String.Empty;
}

assign the variable with MySql

I want to assign my variable [vPrenom_id_obtenu] by the value that I get in my MySql DB ...
With the following code, I receive an error message :
does not contain a definition for 'ExecuteScalar' ....
string vFistNam_id_get;
string connDataBaseStr = "server=myserver;user=####;database=myDataBase;port=3306;password=dsdfsdfsdf123;";
string sqlDataBaseSelect = "SELECT column_fistname_id FROM table_identy WHERE column_famillyname='" + vFamillyName + "'";
MySqlConnection connDataBase = new MySqlConnection(connDataBaseStr);
connDataBase.Open();
vFistNam_id_get = (string)connDataBase.ExecuteScalar();
connDataBase.Close();
How can I retrieve the value that is in "column_fistname_id"?
The type of two columns of my table
Le type de deux colonnes de ma table [column_fistname_id] and [column_famillyname] is «text'.
ExecuteScalar is a method to call on an instance of a MySqlCommand not of a MySqlConnection
The right way to go is:
using(MySqlConnection connDataBase = new MySqlConnection(connDataBaseStr))
{
connDataBase.Open();
MySqlCommand cmd = new MySqlCommand(sqlDataBaseSelect, connDataBase);
vFistNam_id_get = (string)cmd.ExecuteScalar();
}
However your code is wrong for another reason.
this sql string
string sqlDataBaseSelect = "SELECT column_fistname_id FROM table_identy " +
"WHERE column_famillyname='" + vFamillyName + "'";
leads the way to SqlInjection
You should rewrite it in this way
string sqlDataBaseSelect = "SELECT column_fistname_id FROM table_identy " +
"WHERE column_famillyname=?family";
and then before calling ExecuteScalar add a Parameter to the command
cmd.Parameters.AddWithValue("?family", vFamillyName);
And as added value you don't have to worry about datatype delimiter (single quote in this case)
You need to use MySqlCommand to use ExecuteScalar. You're also missing the SQL in your source code, i.e. select * from something, or a stored proc name.
public static int GetNumRows(String OrchardName)
{
// Create Connection
MySqlConnection con = new MySqlConnection(_connectionString);
// Create Command
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT COUNT(*) FROM orchards WHERE OrchardName = #OrchardName";
cmd.Parameters.Add("#OrchardName", OrchardName);
// Return Count
con.Open();
Int32 NumRows = (Int32)cmd.ExecuteScalar();
return NumRows;
}
Example:
MySqlConnection connDataBase = new MySqlConnection(connDataBaseStr);
connDataBase.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT column_fistname_id FROM table_identy WHERE column_famillyname='" + vFamillyName + "'";
MySqlDataReader reader = command.ExecuteReader();
string vFistNam_id_get = null;
while (reader.Read())
{
vFistNam_id_get = (int)reader["column_fistname_id"];
}
You're using the ADO.NET types wrong. The easiest thing to do would be to use the MySqlHelper static methods, like this:
string vFistNam_id_get = (string)
MySqlHelper.ExecuteScalar(dbConnString, "select `col1` from `table1`");

Why do I error out when trying to retrieve a result set with DotConnect components?

With the code below I get, "ORA-01036: illegal variable name/number" on the call to ExecuteReader:
cmd.Parameters.Add("cur", Devart.Data.Oracle.OracleDbType.Cursor);
cmd.Parameters["cur"].Direction = ParameterDirection.Output;
Devart.Data.Oracle.OracleCursor oraCursor =
(Devart.Data.Oracle.OracleCursor)cmd.Parameters["cur"].Value;
Devart.Data.Oracle.OracleDataReader odr = cmd.ExecuteReader();
while (odr.Read()) {
ACurrentUserRoles.Add(odr.GetString(0));
}
What I want to do is populate a List with the result of the query. I don't see any examples for that in DevArt's documentation (or googling). I had it working with Oracle's ODP components with:
OracleDataReader odr = cmd.ExecuteReader();
while (odr.Read())
{
ACurrentUserRoles.Add(odr.GetString(0));
}
...but can't find the parallel working with DotConnect components.
Updated:
Okay, here's the entire method (ACurrentUserRoles is a List of Strings):
public void PopulateCurrentUserRoles(String AUserName, List<String> ACurrentUserRoles) {
_UserName = AUserName;
String query = "select roleid from ABCrole where ABCid = :ABCID";
Devart.Data.Oracle.OracleCommand cmd = new Devart.Data.Oracle.OracleCommand(query, con);
cmd.CommandType = CommandType.Text;
int _ABCID = GetABCIDForUserName();
cmd.Parameters.Add("ABCID", _ABCID);
cmd.Parameters["ABCID"].Direction = ParameterDirection.Input;
cmd.Parameters["ABCID"].DbType = DbType.String;
cmd.Parameters.Add("cur", Devart.Data.Oracle.OracleDbType.Cursor);
cmd.Parameters["cur"].Direction = ParameterDirection.Output;
//cmd.ExecuteNonQuery(); blows up: "illegal variable name/number"
//cmd.ExecuteCursor(); " "
//cmd.ExecuteReader(); " "
Devart.Data.Oracle.OracleCursor oraCursor =
(Devart.Data.Oracle.OracleCursor)cmd.Parameters["cur"].Value;
Devart.Data.Oracle.OracleDataReader odr = oraCursor.GetDataReader(); // "Object reference not set to an instance of an object"
while (odr.Read()) {
ACurrentUserRoles.Add(odr.GetString(0));
}
}
The err msgs I'm getting are appended as comments to the lines where they occur.
First, why are you adding a cursor type parameter and then totally ignore it?.
Second, I have never seen this use of cursor with the ExecuteReader but with the ExecuteNonQuery.
For example:
string cmdText = "begin open :cur for select * from dept; end;";
OracleCommand oraCommand = new OracleCommand(cmdText, oraConnection);
oraCommand.Parameters.Add("cur", OracleDbType.Cursor);
oraCommand.Parameters["cur"].Direction = ParameterDirection.Output;
oraCommand.ExecuteNonQuery();
OracleCursor oraCursor = (OracleCursor)oraCommand.Parameters["cur"].Value;
oraDataAdapter.Fill(dataSet, "Table", oraCursor);
So probably your exception derives from the use of ExecuteReader
This is another example taken directly from the site of DevArt:
string cmdText = "begin open :cur1 for select * from dept;" +
"open :cur2 for select * from emp; end;";
OracleCommand oraCommand = new OracleCommand(cmdText, oraConnection);
oraCommand.Parameters.Add("cur1", OracleDbType.Cursor);
oraCommand.Parameters["cur1"].Direction = ParameterDirection.Output;
oraCommand.Parameters.Add("cur2", OracleDbType.Cursor);
oraCommand.Parameters["cur2"].Direction = ParameterDirection.Output;
oraDataAdapter.SelectCommand = oraCommand;
oraDataAdapter.Fill(dataSet);

how to return int value from select query in function?

I need to retrieve Ticket_Id from tbl_Ticket to pass into body section of sending email function..
Is the below code correct?
every times i get Ticket_Id 1..
public int select_TicketId(){
string strConn = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString.ToString();
SqlConnection sqlCon = new SqlConnection(strConn);
string getId = ("select Ticket_Id from tbl_Ticket where Client_EmailAdd='" + objNewTic_BAL.email + "' ");
sqlCon.Open();
SqlCommand cmd1 = new SqlCommand(getId, sqlCon);
int i=cmd1.ExecuteNonQuery();
return i;
}
You are searching for ExecuteScalar which returns the first value.
using System.Configuration;
//
public int select_TicketId()
{
string strConn = ConfigurationManager.ConnectionStrings["conString"].ConnectionString.ToString();
SqlConnection sqlCon = new SqlConnection(strConn);
string getId = ("select TOP 1 Ticket_Id from tbl_Ticket where Client_EmailAdd='" + objNewTic_BAL.email + "' ");
sqlCon.Open();
SqlCommand cmd1 = new SqlCommand(getId, sqlCon);
return Convert.ToInt32(cmd1.ExecuteScalar());
}
Also use CommandProperties to set the where statement for better security, like below:
public int select_TicketId()
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
int result = -1;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "select TOP 1 Ticket_Id from tbl_Ticket where Client_EmailAdd=#email";
command.Parameters.Add("#email", SqlDbType.Text).Value = objNewTic_BAL.email;
result = Convert.ToInt32(command.ExecuteScalar());
}
return result;
}
You should call int i=(int)cmd1.ExecuteScalar(); method
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx
You're calling ExecuteNonQuery. But it's a query. This should have rung some warning bells :)
Try ExecuteScalar instead, and cast the result to int...
return (int) cmd1.ExecuteScalar();
Note that you should use using statements for the command and connection as well, so that both are closed appropriately.
And (I hadn't spotted this before) you should definitely use parameterized SQL instead of including a value directly into your SQL. Otherwise you're open to SQL Injection attacks...
So something like:
private const string FetchTicketIdSql =
"select Ticket_Id from tbl_Ticket where Client_EmailAdd = #Email";
public int FetchTicketId()
{
// No need for ToString call...
string connectionString =
ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(connection, FetchTicketIdSql))
{
command.Parameters.Add("#Email", SqlDbType.NVarChar).Value =
bjNewTic_BAL.email;
return (int) command.ExecuteScalar();
}
}
}
You should consider what you want to happen if there isn't exactly one result though...
Hiral,
ExecuteNonQuery in
int i=cmd1.ExecuteNonQuery();
will return number of records that satisfy your query. In this case it is 1 (or 0 if there are no emails)
Try using ExecuteReader instead.

Categories