How to use parameters in IN Clause sql informix - c#

How to use parameters in IN Clause sql informix
StringBuilder cmdTxt = new StringBuilder();
cmdTxt.Append(" SELECT COUNT(emp_num) ");
cmdTxt.Append(" FROM tbl1 WHERE year IS NULL AND calc_year = ? AND camp IN (,,,)");
using (var myIfxCmd = new IfxCommand(cmdTxt.ToString(), con))
{
myIfxCmd.CommandType = CommandType.Text;
myIfxCmd.Parameters.Add("calc_year", IfxType.Integer);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
myIfxCmd.Parameters[0].Value = calcYear;
res = int.Parse(myIfxCmd.ExecuteScalar().ToString());
}
I don't know how to handle passing parameters to camp IN (,,,,)//Set of numbers

I've something like this
IDbCommand cmd = connection.CreateCommand(); //connection has been instantiated
cmd.CommandTimeout = connection.ConnectionTimeout;
var query = #"SELECT COUNT(emp_num)
FROM tbl1 WHERE year IS NULL AND calc_year = #year AND camp IN ({0})";
cmd.Parameters.Add(new SqlParameter("#year", calcYear));
var sb = new StringBuilder();
//ids is a list/array of ids i want in the in clause
for (int i = 0; i < ids.Count; i++)
{
sb.AppendFormat("#p{0},", i);
cmd.Parameters.Add(new SqlParameter("#p" + i, ids[i]));
}
if (sb.Length > 0) { sb.Length -= 1; }
string cmdText = string.Format(query, sb.ToString());
cmd.CommandText = cmdText;
cmd.Connection = connection;
var reader = cmd.ExecuteReader();

Related

How to use one Column of Sql query into another sql query inside C# Code

How to use query1 column Display Group into query 2 in the below c# code.
I have denoted the place where i want to put query1 column by ???? symbol.
public class PopulateRangeInStore
{
[Test]
[Category(TestType.NeedsDeployment)]
public void PopulateRangeInStores()
{
ExecutePopulateRangeInStoreProcedure("csg_sp_populate_RangeInStore");
using (var connection = IKBDatabaseConnection.GetConnectionForIKBTFS())
{
string query1 = "SELECT count (distinct DESC7) FROM ix_spc_planogram (NOLOCK) WHERE dbstatus= 1";
string query2 = "SELECT count (distinct EquipmentType) FROM Csg_Range_In_Store (NOLOCK) WHERE DisplayGroup = '" + ?????+ "'";
var command1 = new SqlCommand(query1, connection);
var command2 = new SqlCommand(query2, connection);
//string output = " ";
//var = " ";
//var actualDG = " ";
var actualDG = " ";
var expectedDG = " ";
var dataReader1 = command1.ExecuteReader();
var dataReader2 = command2.ExecuteReader();
if (dataReader1.Read())
{
DataTable dt = new DataTable();
dt.Load(dataReader1);
expectedDG = dt.Rows.Count.ToString();
}
if (dataReader2.Read())
{
DataTable dt = new DataTable();
dt.Load(dataReader2);
actualDG = dt.Rows.Count.ToString();
}
actualDG.Should().Be(expectedDG);
}
}
private void ExecutePopulateRangeInStoreProcedure(string storedProcedure)
{
using (var connection = IKBDatabaseConnection.GetConnectionForIKBTFS())
{
using (SqlCommand cmd = new SqlCommand(storedProcedure, connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ix_sys_error", SqlDbType.Int).Value = 0;
cmd.CommandTimeout = 0;
cmd.ExecuteNonQuery();
}
}
}
}
You can solve it by creating a subquery in the place of ???
string query2 = "SELECT count (distinct EquipmentType) FROM Csg_Range_In_Store (NOLOCK) WHERE DisplayGroup in (" + query2 +")";

Using for loop to delete data in database

I want to delete every item in the array from the database.
string[] ids = dt.AsEnumerable()
.Select(row => row["ProductID"].ToString())
.ToArray();
for (int i = 0; i <= ids.Length; i++) {
string val = ids[i];
MySqlCommand cmd1 = new MySqlCommand();
cmd1.CommandText = "Delete from tblindividualproduct where ProductID = #p1";
cmd1.Parameters.AddWithValue("#p1", val);
}
When I run this the line
string val = ids[i];
gives me an error which says:
Index was outside the bounds of the array.
What's wrong with this?
This is my whole code UPDATED
string connString = "Server=192.168.1.100;Database=product;Uid=newuser;Pwd=password";
MySqlConnection conn = new MySqlConnection(connString);
string[] ids = dt.AsEnumerable()
.Select(row => row["ProductID"].ToString())
.ToArray();
try
{
MySqlCommand cmd1 = new MySqlCommand();
conn.Open();
cmd1.CommandText = "Delete from tblindividualproduct where ProductID = #p1";
cmd1.Parameters.AddWithValue("#p1", "");
for (int i = 0; i < ids.Length; i++)
{
string val = ids[i];
cmd1.Parameters[0].Value = val;
cmd1.ExecuteNonQuery();
}
MessageBox.Show("Checkout Successful");
}
Arrays in .NET are zero based and thus the valid indexes go from zero to length - 1.
You should change your code to
for (int i = 0; i < ids.Length; i++)
As pointed by other answer you loop also fails to call cmd1.ExecuteNonQuery and it seems that you don't have associated a connection to the MySqlCommand (thus it will not work at all).
An interesting variation on your code could be to create a single string with all of your commands and submit the command just one time.
Beware that this is not recommended unless you are absolutely sure that your ID are just numbers and not coming from user input
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= ids.Length; i++)
sb.AppendFormat("Delete from tblindividualproduct where ProductID = {0};", ids[i]);
MySqlCommand cmd1 = new MySqlCommand();
cmd1.CommandText = sb.ToString();
cmd1.Connection = connection;
cmd1.ExecuteNonQuery();
Array indexes go from 0 up to Length - 1, so you need to stop the loop before i == ids.Length. Try replacing the <= with <. Also, don't forget to call ExecuteNonQuery to execute your command.
for (int i = 0; i < ids.Length; i++) {
string val = ids[i];
MySqlCommand cmd1 = new MySqlCommand(conn);
cmd1.CommandText = "Delete from tblindividualproduct where ProductID = #p1";
cmd1.Connection = conn;
cmd1.Parameters.AddWithValue("#p1", val);
cmd1.ExecuteNonQuery();
}
You can also set up the command outside of the loop and only set the parameter and execute the command inside the loop:
MySqlCommand cmd1 = new MySqlCommand(conn);
cmd1.CommandText = "Delete from tblindividualproduct where ProductID = #p1";
cmd1.Connection = conn;
cmd1.Parameters.AddWithValue("#p1", "");
for (int i = 0; i < ids.Length; i++) {
string val = ids[i];
cmd1.Parameters[0].Value = val;
cmd1.ExecuteNonQuery();
}
This will be much more efficient as there's only one call to the DB, plus there's no need anymore to iterate through yours ids collection.
string[] ids = dt.AsEnumerable()
.Select(row => row["ProductID"].ToString())
.ToArray();
MySqlCommand cmd1 = new MySqlCommand();
cmd1.CommandText = "Delete from tblindividualproduct where ProductID IN (" + String.Join(",", ids) + ")";
Your index goes from 0 to your length -1 like this:
tring[] ids = dt.AsEnumerable()
.Select(row => row["ProductID"].ToString())
.ToArray();
for (int i = 0; i < ids.Length; i++) {
string val = ids[i];
MySqlCommand cmd1 = new MySqlCommand();
cmd1.CommandText = "Delete from tblindividualproduct where ProductID = #p1";
cmd1.Parameters.AddWithValue("#p1", val);
}
And Index was outside the bounds of the array. means that your accessed an element that does not exist with that index.

Displaying a single row from access database in c#

i have a project, and part of it asks the user to input the ID of the patient to show his/her details
This is my code
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=hospital database.accdb";
dbConn = new OleDbConnection(sConnection);
dbConn.Open();
sql = "SELECT * FROM Patients";
dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Connection = dbConn;
dbReader = dbCmd.ExecuteReader();
listBox1.Items.Clear();
if (dbReader.HasRows)
{
while (dbReader.Read())
{
if (dbReader["PatientID"] != DBNull.Value)
{
int anInteger;
anInteger = Convert.ToInt32(textBox7.Text);
anInteger = int.Parse(textBox7.Text);
if (anInteger == 101)
{
}
}
}
}
in the IF statement, i dont know what to write in it, to display on the row of the patient with this ID only
Please Help!!
Instead of selecting all rows, it is much more efficient to filter the one row you are looking for using a parameter and modifying your SQL statement as follows.
sql = "SELECT * FROM Patients WHERE PatientID = [pID]";
dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Connection = dbConn;
dbcmd.Parameters.AddWithValue("pID", 101);
dbReader = dbCmd.ExecuteReader();
I would also suggest looking into the "using" clause. Here's a SO example.
sql = "SELECT Count(*) FROM Patients WHERE PatientID = #PID";
dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Connection = dbConn;
dbcmd.Parameters.AddWithValue("#PID", 101);
Int32 Cnt = dbCmd.ExecuteScalar();
if ( Cnt > 0)
{
// Do Something
}
else { // Do something}
you have to use a variable to be sure that your ID was found and and break; to exit your loop once it was found
if (dbReader.HasRows)
{
bool found = false;
while (dbReader.Read())
{
if (dbReader["PatientID"] != DBNull.Value)
{
int anInteger;
anInteger = Convert.ToInt32(textBox7.Text);
anInteger = int.Parse(textBox7.Text);
if (anInteger == 101)
{
found = true ; Break;
}
}
}
}
int anInteger = Convert.ToInt32(textBox7.Text);
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=hospital database.accdb";
dbConn = new OleDbConnection(sConnection);
dbConn.Open();
sql = "SELECT * FROM Patients where PatientID=#PatientID";
dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Parameters.AddWithValue("#PatientID",anInteger);
dbCmd.Connection = dbConn;
dbReader = dbCmd.ExecuteReader();
listBox1.Items.Clear();
while (dbReader.Read())
{
//now display the reader values here : sample
//TextBox1.Text=dbReader["name"].ToString();
}

SqlDataAdapter is giving me 0 results

SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd = CreateParameterizedQuery();
SqlDataAdapter dap = new SqlDataAdapter();
dap.SelectCommand = cmd;
DataTable tbl = new DataTable();
dap.Fill(tbl);
if (tbl.Rows.Count > 0)
{
grid.DataSource = tbl;
}
The actual SQL Query will produce results in SQL Management Studio. However I am getting 0 Rows of Data. I set a breakpoint at tbl.Rows.Count and I see it's 0 and stepping will skip the necessary code to set the DataSource.
private SqlCommand CreateParameterizedQuery()
{
SqlCommand command = new SqlCommand();
string[] allTheseWords;
if (textBoxAllTheseWords.Text.Length > 0)
{
allTheseWords = textBoxAllTheseWords.Text.Split(' ');
string SQLQuery = "SELECT distinct [databaseName].[dbo].[customerTable].[name], [databaseName].[dbo].[customerTable].[dos], [databaseName].[dbo].[customerTable].[ACC], [databaseName].[dbo].[reportTable].[id], [databaseName].[dbo].[reportTable].[ACC], [databaseName].[dbo].[reportTable].[fullreport] FROM [databaseName].[dbo].[reportTable], [databaseName].[dbo].[customerTable] WHERE ";
int i = 0;
foreach (string word in allTheseWords)
{
var name = "#word" + (i++).ToString();
command.Parameters.AddWithValue(name, "'%" + word + "%'");
SQLQuery = SQLQuery + String.Format(" [databaseName].[dbo].[reportTable].[fullreport] LIKE {0} AND ", name);
}
SQLQuery = SQLQuery + " [databaseName].[dbo].[customerTable].[ACC] = [databaseName].[dbo].[reportTable].[ACC]";
command.CommandText = SQLQuery;
}
return command;
}
I am using WinForm with C# on Windows 8.
The SQLQuery variable contains this data when debugging
SELECT distinct [databaseName].[dbo].[customerTable].[name], [databaseName].[dbo].[customerTable].[dos], [databaseName].[dbo].[customerTable].[ACC], [databaseName].[dbo].[reportTable].[customerID], [databaseName].[dbo].[reportTable].[ACC], [databaseName].[dbo].[reportTable].[fullreport] FROM [databaseName].[dbo].[reportTable], [databaseName].[dbo].[customerTable] WHERE [databaseName].[dbo].[reportTable].[fullreport] LIKE #word0 AND [databaseName].[dbo].[customerTable].[ACC] = [databaseName].[dbo].[reportTable].[ACC]
debugMySQL is a method that spits out the SQL Query with the parameters substituted
public void debugMySQL()
{
string query = command.CommandText;
foreach (SqlParameter p in command.Parameters)
{
query = query.Replace(p.ParameterName, p.Value.ToString());
}
textBox1.Text = query;
}
The output looks like
SELECT distinct [databaseName].[dbo].[customerTable].[name], [databaseName].[dbo].[customerTable].[dos], [databaseName].[dbo].[customerTable].[ACC], [databaseName].[dbo].[reportTable].[id], [databaseName].[dbo].[reportTable].[ACC], [databaseName].[dbo].[reportTable].[fullreport] FROM [databaseName].[dbo].[reportTable], [databaseName].[dbo].[customerTable] WHERE [databaseName].[dbo].[reportTable].[fullreport] LIKE '%single%' AND [databaseName].[dbo].[customerTable].[ACC] = [databaseName].[dbo].[reportTable].[ACC]
You can see parametrized query with its argument value using SQL Profiler.

How do multi rows insert with MySqlCommand and prepare statement?(#C)

Mysql give example how insert rows with prepare statement and .NET:
http://dev.mysql.com/doc/refman/5.5/en/connector-net-programming-prepared.html
Its looks that its works like that,because in the end of each iteration call to:cmd.ExecuteNonQuery():
INSERT INTO VALUES()...;INSERT INTO VALUES()...;INSERT INTO VALUES()...;
Can it done with use of prepare statement like that:
INSERT INTO all values...
More explanations::
The code in mysql example (cmd.ExecuteNonQuery() in each iteration):
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
conn = new MySql.Data.MySqlClient.MySqlConnection();
cmd = new MySql.Data.MySqlClient.MySqlCommand();
conn.ConnectionString = strConnection;
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO myTable VALUES(NULL, #number, #text)";
cmd.Prepare();
cmd.Parameters.AddWithValue("#number", 1);
cmd.Parameters.AddWithValue("#text", "One");
for (int i=1; i <= 1000; i++)
{
cmd.Parameters["#number"].Value = i;
cmd.Parameters["#text"].Value = "A string value";
cmd.ExecuteNonQuery();
}
}
*The code that i want to have like that(cmd.ExecuteNonQuery(); after all iterations): *
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
conn = new MySql.Data.MySqlClient.MySqlConnection();
cmd = new MySql.Data.MySqlClient.MySqlCommand();
conn.ConnectionString = strConnection;
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO myTable VALUES(NULL, #number, #text)";
cmd.Prepare();
cmd.Parameters.AddWithValue("#number", 1);
cmd.Parameters.AddWithValue("#text", "One");
for (int i=1; i <= 1000; i++)
{
cmd.Parameters["#number"].Value = i;
cmd.Parameters["#text"].Value = "A string value";
}
cmd.ExecuteNonQuery();
}
Try this:
using (var connection = new MySqlConnection("your connection string"))
{
connection.Open();
// first we'll build our query string. Something like this :
// INSERT INTO myTable VALUES (NULL, #number0, #text0), (NULL, #number1, #text1)...;
StringBuilder queryBuilder = new StringBuilder("INSERT INTO myTable VALUES ");
for (int i = 0; i < 10; i++)
{
queryBuilder.AppendFormat("(NULL,#number{0},#text{0}),", i);
//once we're done looping we remove the last ',' and replace it with a ';'
if (i == 9)
{
queryBuilder.Replace(',', ';', queryBuilder.Length - 1, 1);
}
}
MySqlCommand command = new MySqlCommand(queryBuilder.ToString(), connection);
//assign each parameter its value
for (int i = 0; i < 10; i++)
{
command.Parameters.AddWithValue("#number" + i, i);
command.Parameters.AddWithValue("#text" + i, "textValue");
}
command.ExecuteNonQuery();
}

Categories