Sql Select Statement with Paging c# - c#

What is the correct way of writing a select statment on c# controller for paging. This is the best I came up with, but I know it doesn't work because it's showing all data on my first page on the grid... please help
public JsonResult getData(int start, int limit)
{
List<MyItem> items = new List<MyItem>();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices1"].ConnectionString))
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT State, Capital FROM MYDBTABLE";
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
MyItem item = new MyItem();
item.State = reader[0].ToString();
item.Capital = reader[1].ToString();
items.Add(item);
}
con.Close();
if ((start + limit) > Myitem.Count)
{
limit = Myitem.Count - start;
}
return Json(new { myTable = items }, JsonRequestBehavior.AllowGet);
}
}

Here's the template for stored procs that I like to use for paging.
CREATE PROCEDURE [dbo].[StoredProcName]
#page_size INT
, #page_num INT
AS
BEGIN
SET NOCOUNT ON;
; WITH RESULTS AS
(
SELECT *
, ROW_NUMBER() OVER (ORDER BY <order_col> DESC) AS rn
, ROW_NUMBER() OVER (ORDER BY <order_col> ASC) AS rn_reversed
FROM <table>
)
SELECT *
, CAST(rn + rn_reversed - 1 AS INT) AS total_rows
, CAST(CASE (rn + rn_reversed - 1) % #page_size
WHEN 0 THEN (rn + rn_reversed - 1) / #page_size
ELSE ((rn + rn_reversed - 1) / #page_size) + 1
END AS INT) AS total_pages
FROM RESULTS a
WHERE a.rn BETWEEN 1 + ((#page_num - 1) * #page_size) AND #page_num * #page_size
ORDER BY rn ASC
END
You just need to pass in page_size and page_num to the stored proc and you're good to go.

You could use Linq and use Skip() and Take() like this:
public JsonResult getData(int page, int limit)
{
DataTable dt = new DataTable();
using (SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices1"].ConnectionString))
{
using (SqlCommand cmd = cnn.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT State, Capital FROM MYDBTABLE";
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
int start = (page * limit) - limit;
List<MyItem> items = (from DataRow row in dt.Rows
select new MyItem
{
State = row["State"].ToString(),
Capital = row["Capital"].ToString()
}).Skip(start - 1).Take(limit).ToList();
return Json(new { myTable = items }, JsonRequestBehavior.AllowGet);
}

The basic template I use is:
SELECT ROW_NUMBER(), <Rest of your columns>
FROM <Your Tables/Joins>
WHERE ROW_NUMBER() >= (#PageNum * #RowsPerPage)
AND ROW_NUMBER() < (#PageNum+1 * #RowsPerPage)

Related

Replacing if (Convert.ToString(rdr["Data"]) != bItems)

I want to replace if (Convert.ToString(rdr["Data"]) != bItems) with something that would check if data already exist in my database or not to make process faster as going in that loop taking too much time for bigger database. Plz HELP!
for (int p = 0; p < 256; p++) {
bItems += "P" + buffer[p];
}
using (SQLiteConnection con = new SQLiteConnection(databaseObject.myConnection)) {
con.Open();
SQLiteCommand cmd = new SQLiteCommand("select ID, Data from B where Data like 'P%'", con);
var rdr = cmd.ExecuteReader();
while (rdr.Read()) {
if (Convert.ToString(rdr["Data"]) != bItems) {
SQLiteCommand cmd1 = new SQLiteCommand("INSERT INTO B ('Data') SELECT #Data WHERE NOT EXISTS (SELECT ID, Data FROM B WHERE Data = #Data)", con);
cmd1.Parameters.AddWithValue("#Data", bItems);
cmd1.ExecuteNonQuery();
}
else (Convert.ToString(rdr["Data"]) == bItems) {
sItems = "B" + Convert.ToString(rdr["ID"]);
rdr.Close();
break;
}
}
}
bItems = "";
Console.WriteLine(sItems);
}
instead of reading each row and check the data against bItems. You may need to either query the table to see if there is any record matches bItems, if not then insert it. Or, you can simply insert the data if not exists (which what you did in the first condition.
To simplify your work, you can do this :
// insert the new item if not exists in the table
// returns the item Id
private int InsertDataIfNotExists(string bItems)
{
using (SQLiteConnection connection = new SQLiteConnection(databaseObject.myConnection))
using(SQLiteCommand command = new SQLiteCommand("INSERT INTO B ('Data') SELECT #Data WHERE NOT EXISTS (SELECT 1 FROM B WHERE Data = #Data);", con))
{
connection.Open();
command.Parameters.AddWithValue("#Data", bItems);
// insert data if not exists
command.ExecuteNonQuery();
// get the data's Id
cmd.CommandText = "SELECT ID FROM B WHERE Data = #Data LIMIT 1;";
cmd.Parameters.AddWithValue("#Data", bItems);
var result = cmd.ExecuteScalar()?.ToString();
return int.TryParse(result, out int id) && id > 0 ? id : -1;
}
}
with the above, you only insert the data if not exists, and then return the id.
usage :
var insertResultId = InsertDataIfNotExists(bItems);
if(insertResultId == -1)
{
// handle exceptions
}
else
{
Console.WriteLine(insertResultId);
}

simplifying non-parametrized mysql queries

I have a problem with mySql query below
SELECT name, hospitalID, currentAvgRating, rank
FROM ( SELECT name,hospitalID,currentAvgRating,city,
#curRank := #curRank + 1 AS rank
FROM hospitals h, ( SELECT #curRank := 0) r
ORDER BY currentAvgRating DESC
) toplist
WHERE toplist.hospitalID = #hospitalID
and city = #city
This query I am using to find the rank of particular item & it is working properly. But while runining in program I get Fatal errors of Parameter '#curRank' must be defined. But that is mysql syntax then how can I get it's parameters?
UPDATE
string str = "SELECT name, hospitalID, currentAvgRating, rank FROM (SELECT name,hospitalID,currentAvgRating,city,#curRank := #curRank + 1 AS rank FROM hospitals h, (SELECT #curRank := 0) r ORDER BY currentAvgRating DESC) toplist WHERE toplist.hospitalID = #hospitalID and city = #city";
con.Open();
MySqlCommand cmd = new MySqlCommand(str, con);
cmd.Parameters.AddWithValue("#hospitalID", generalID.Text);
cmd.Parameters.AddWithValue("#city", cityName.Text);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
You can get the rank for a particular hospital/city pair without a rank. Here is a close approximation to your query:
select count(*) + 1 as ranking
from hospitals h cross join
(select h.currentAvgRating
from hospitals h
where h.hospitalID = #hospitalID and h.city = #city
) hh
where h.currentAvgRating > hh.currentAvgRating;
Unlike your code, this gives all hospitals with the same rating, the same ranking.
If you don't want to change the code, then refer to this answer. Actually, I'll quote the relevant part:
I have to add
;Allow User Variables=True
to the connection string
Your SQL is correct I think there are conflect with C# command parameter and mySQL parameter
try this modification of SQL code like this
SELECT name, hospitalID, currentAvgRating, rank
FROM ( SELECT name,hospitalID,currentAvgRating,city,
#curRank := #curRank + 1 AS rank
FROM hospitals h, ( SELECT #curRank := 0) r
ORDER BY currentAvgRating DESC
) toplist
WHERE toplist.hospitalID = ?hospitalID
and city = ?city
you c# like this
string str = <Example Above>;
con.Open();
MySqlCommand cmd = new MySqlCommand(str, con);
cmd.Parameters.AddWithValue("?hospitalID", generalID.Text);
cmd.Parameters.AddWithValue("?city", cityName.Text);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
Just changeing the C# command parameter using ? than using #

SQL update command in c#

I have a SQL Server table with columns like this:
Mobile No <> OTP <> GenTime <> AuthTime <> IsAuth
9632587410 <> 256389 <> ****** <> ******** <> False
9876543210 <> 258963 <> ***** <> ****** <> False
so on ...
using (SqlConnection conn = new SqlConnection())
{
string inputn = Console.ReadLine();
long mobileNo;
long.TryParse(inputn, out mobileNo);
string inputo = Console.ReadLine();
int OTP;
Int32.TryParse(inputo, out OTP);
DateTime now = DateTime.Now;
conn.ConnectionString = "Data Source=10.0.0.98;Initial Catalog=TeletextCMS_Dev;User ID=Testteam;Password=Cognigent33#";
conn.Open();
//long r = 8947052876;
SqlCommand command = new SqlCommand("SELECT * FROM CustomerAuthOTP WHERE MobileNum=" + mobileNo, conn);
int f = 0;
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
//int OTP = reader[1];
int OTPGen = int.Parse(string.Format("{0}", reader[1]));
int a = now.Hour;
int b = now.Minute;
int e = now.Day;
DateTime then = DateTime.Parse(string.Format("{0}", reader[2]));
int c = then.Hour;
int d = then.Minute;
int g = then.Day;
if (e == g)
{
int t = (a - c) * 60 + b - d;
if (OTP == OTPGen && e == g && t <= 15)
{
Console.WriteLine("Hi");
f = 1;
}
else
{
Console.WriteLine("No");
}
}
if (e > g)
{
int t = (a + 24 - c) * 60 + b - d;
if (OTP == OTPGen && e == g && t <= 15)
{
Console.WriteLine("Hi");
f = 1;
}
else
{
Console.WriteLine("No");
}
}
}
}
if(f == 1)
{
SqlCommand cmd = new SqlCommand("UPDATE CustomerAuthOTP SET IsAuthenticated=True, AuthenticationTime=" + now, conn);
Console.WriteLine("Hi");
}
}
Now at the bottom I have an Update command. I tried to execute it but it is not doing anything.
There is no error in the code. Kindly some one help me out if f== 1 then in the CustomerAuthOTP table update the IsAuthenticated value to be true and also set the authentication time to now.DateTime()
First of all you should execute your commnd:
SqlCommand cmd = new SqlCommand("UPDATE CustomerAuthOTP SET IsAuthenticated=True, AuthenticationTime=" + now, conn);
cmd.ExecuteNonQuery();
I recommend to use SqlCommand.Parameters
var commandText = "UPDATE CustomerAuthOTP SET IsAuthenticated=#IsAuthenticated, AuthenticationTime=#AuthenticationTime";
SqlCommand cmd = new SqlCommand(commandText, conn);
cmd.Parameters.AddWithValue("#IsAuthenticated", true);
cmd.Parameters.AddWithValue("#AuthenticationTime", now);
cmd.ExecuteNonQuery();
It'll help SQL provider to determine parameter types and protects against SQL-injections.
DateTime now = DateTime.Now;
...
SqlCommand cmd = new SqlCommand(
"UPDATE CustomerAuthOTP SET IsAuthenticated=True, AuthenticationTime="
+ now, conn);
Note that this will be a string concatenation, and (depending on your locale, etc), the following is not valid TSQL:
UPDATE CustomerAuthOTP SET IsAuthenticated=True, AuthenticationTime=08/12/2015 12:08:32
The immediate problem is formatting (both the datetime and the boolean are wrong), but it is best fixed by parameterization - you should almost never be concatenating values into TSQL:
SqlCommand cmd = new SqlCommand(
"UPDATE CustomerAuthOTP SET IsAuthenticated=1, AuthenticationTime=#now", conn);
cmd.Parameters.AddWithValue("now", now);
cmd.ExecuteNonQuery();
Or with a tool like "dapper":
conn.Execute("UPDATE CustomerAuthOTP SET IsAuthenticated=1, AuthenticationTime=#now",
new { now });

How can I determine if column of a stored procedure result can be null

I'm writing a code generator and am getting stuck on determining the nullable status of a stored procedure result set Column. I can query the DataType just fine but neither the datareader object nor a data table column contain the correct nullable value of my column.
public List<DataColumn> GetColumnInfoFromStoredProcResult(string schema, string storedProcName)
{
//build sql text
var sb = new StringBuilder();
sb.Append("SET FMTONLY OFF; SET FMTONLY ON; \n");//this is how EF4.1 did so I copied..not sure why the repeat
sb.Append(String.Format("exec {0}.{1} ", schema, storedProcName));
var prms = GetStoredProcedureParameters(schema: schema, sprocName: storedProcName);
var count = 1;
foreach (var param in prms)
{
sb.Append(String.Format("{0}=null", param.Name));
if (count < prms.Count)
{
sb.Append(", ");
}
count++;
}
sb.Append("\n SET FMTONLY OFF; SET FMTONLY OFF;");
var dataTable = new DataTable();
//var list = new List<DataColumn>();
using (var sqlConnection = this.SqlConnection)
{
using (var sqlAdapter = new SqlDataAdapter(sb.ToString(), sqlConnection))
{
if (sqlConnection.State != ConnectionState.Open) sqlConnection.Open();
sqlAdapter.SelectCommand.ExecuteReader(CommandBehavior.KeyInfo);
sqlConnection.Close();
sqlAdapter.Fill(dataTable);
}
//using (var sqlCommand = new SqlCommand())
//{
// sqlCommand.CommandText = sb.ToString();
// sqlCommand.CommandType = CommandType.Text;
// sqlCommand.Connection = sqlConnection;
// if (sqlConnection.State != ConnectionState.Open) sqlConnection.Open();
// var dr = sqlCommand.ExecuteReader(CommandBehavior.SchemaOnly);
// var whateva = dr.GetSchemaTable();
// foreach (DataColumn col in whateva.Columns)
// {
// list.Add(col);
// }
//}
}
var list = dataTable.Columns.Cast<DataColumn>().ToList();
return list;
}
I'm trying to end up with something similar to the the Entities Framework creation of a complex type from a stored procedure. Can I hijack that functionality?
On this example the Id column.. tblJobId (not my naming convention) would never be null.. But I selected null as ImNull and it has all the same properties so how does EF determine if the corresponding C# data type should be nullable or not?
Has anybody done this..
Ideas are appreciated.
The secret was to use Schema Only and fill a dataset not datatable. Now the AllowDbNull property on the datacolumn properly displays the nullable status of the return value.
This was it...
public List<DataColumn> GetColumnInfoFromStoredProcResult(string schema, string storedProcName)
{
//build sql text
var sb = new StringBuilder();
sb.Append("SET FMTONLY OFF; SET FMTONLY ON; \n");//this is how EF4.1 did so I copied..not sure why the repeat
sb.Append(String.Format("exec {0}.{1} ", schema, storedProcName));
var prms = GetStoredProcedureParameters(schema: schema, sprocName: storedProcName);
var count = 1;
foreach (var param in prms)
{
sb.Append(String.Format("{0}=null", param.Name));
if (count < prms.Count)
{
sb.Append(", ");
}
count++;
}
sb.Append("\n SET FMTONLY OFF; SET FMTONLY OFF;");
var ds = new DataSet();
using (var sqlConnection = this.SqlConnection)
{
using (var sqlAdapter = new SqlDataAdapter(sb.ToString(), sqlConnection))
{
if (sqlConnection.State != ConnectionState.Open) sqlConnection.Open();
sqlAdapter.SelectCommand.ExecuteReader(CommandBehavior.SchemaOnly);
sqlConnection.Close();
sqlAdapter.FillSchema(ds, SchemaType.Source, "MyTable");
}
}
var list = ds.Tables[0].Columns.Cast<DataColumn>().ToList();
return list;
}
public List<SqlParamInfo> GetStoredProcedureParameters(string schema, string sprocName)
{
var sqlText = String.Format(
#"SELECT
[Name] = N'#RETURN_VALUE',
[ID] = 0,
[Direction] = 6,
[UserType] = NULL,
[SystemType] = N'int',
[Size] = 4,
[Precision] = 10,
[Scale] = 0
WHERE
OBJECTPROPERTY(OBJECT_ID(N'{0}.{1}'), 'IsProcedure') = 1
UNION
SELECT
[Name] = CASE WHEN p.name <> '' THEN p.name ELSE '#RETURN_VALUE' END,
[ID] = p.parameter_id,
[Direction] = CASE WHEN p.is_output = 0 THEN 1 WHEN p.parameter_id > 0 AND p.is_output = 1 THEN 3 ELSE 6 END,
[UserType] = CASE WHEN ut.is_assembly_type = 1 THEN SCHEMA_NAME(ut.schema_id) + '.' + ut.name ELSE NULL END,
[SystemType] = CASE WHEN ut.is_assembly_type = 0 AND ut.user_type_id = ut.system_type_id THEN ut.name WHEN ut.is_user_defined = 1 OR ut.is_assembly_type = 0 THEN st.name WHEN ut.is_table_type =1 Then 'STRUCTURED' ELSE 'UDT' END,
[Size] = CONVERT(int, CASE WHEN st.name IN (N'text', N'ntext', N'image') AND p.max_length = 16 THEN -1 WHEN st.name IN (N'nchar', N'nvarchar', N'sysname') AND p.max_length >= 0 THEN p.max_length/2 ELSE p.max_length END),
[Precision] = p.precision,
[Scale] = p.scale
FROM
sys.all_parameters p
INNER JOIN sys.types ut ON p.user_type_id = ut.user_type_id
LEFT OUTER JOIN sys.types st ON ut.system_type_id = st.user_type_id AND ut.system_type_id = st.system_type_id
WHERE
object_id = OBJECT_ID(N'{0}.{1}')
ORDER BY 2", schema, sprocName);
using (var sqlConnection = this.SqlConnection)
{
using (var sqlCommand = new SqlCommand())
{
if (sqlConnection.State != ConnectionState.Open) sqlConnection.Open();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandType = CommandType.Text;
sqlCommand.CommandText = sqlText;
var dr = sqlCommand.ExecuteReader();
var result = new List<SqlParamInfo>();
while (dr.Read())
{
if (Convert.ToString(dr["Name"]) != "#RETURN_VALUE")
{
result.Add(new SqlParamInfo(dr));
}
}
return result;
}
}
}
Assume, that every column which comes from SP can be null - this is a valid assumption because stored procedure - its a kind of data abstraction layer and thus its code can change but still produce valid results.
If column was non-nullable yesterday it means nothing for today. So - all the columns which come from SP resultsets are nullable by design.
Update.
Assuming that table t1 has column Id INT IDENTITY PRIMARY KEY
Your stored proc looks like this:
CREATE PROC p1
AS
BEGIN
SELECT Id FROM t1
END
So it will never return an Id = NULL, but this is the SP - an abstraction of data, so - tomorrow i'll modify it like this:
CREATE PROC p1
AS
BEGIN
SELECT Id FROM t1
UNION
SELECT NULL
END
So, now it returns NULL - think about this. The difference in understanding of data abstraction

input parameter to mysql syntax on C#

I try to input value but #numVal doest not work ( on the line begin with arr[10] )
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
MySqlConnection conDatabase = new MySqlConnection("Data Source=localhost;" +
"Persist Security Info=yes;" +
"UserId=tee; PWD=t5794849; database=ph3;");
conDatabase.Open();
// MySqlCommand cmdDatabase = new MySqlCommand("DROP TABLE IF EXISTS `q_mem_sur`; create table q_mem_sur as SELECT Count(*) As rowa, member.Ssurname, Sum(Case When ((member.status = '1')) Then 1 Else 0 End) As Status11 From member Group By member.Ssurname Order By rowa Desc;", conDatabase);
Console.WriteLine("Enter username");
string input = Console.ReadLine();
try
{
int numVal = Convert.ToInt16(input);
}
catch (FormatException )
{
Console.WriteLine("Input string is not a sequence of digits.");
}
catch (OverflowException )
{
Console.WriteLine("The number cannot fit in an Int32.");
}
string[] arr = new string[11];
arr[0] = "UPDATE `member` SET `amphurecode`= SUBSTRING(member.own,3,4)";
arr[1] = "UPDATE `member` SET `provincecode`= SUBSTRING(member.own,3,2)";
arr[2] = "DROP TABLE IF EXISTS `q_mem_tim`; create table q_mem_tim as SELECT member.idmember, member.own, member.provincecode, province.PROVINCE_NAME, member.amphurecode, amphur.AMPHUR_NAME, member.novote, member.Sname, member.Ssurname, member.Hno, member.Moo, member.Sex, member.tambol, member.dateofbirth, member.migratedate, Year( Current_Date( ) ) - Year( member.dateofbirth ) AS y, DATEDIFF('2011-08-01',(migratedate)) AS d FROM member LEFT JOIN amphur ON ( member.amphurecode = amphur.AMPHUR_CODE ) LEFT JOIN province ON member.provincecode = province.PROVINCE_CODE";
arr[3] = "DROP TABLE IF EXISTS `q_mem_sur`; create table q_mem_sur as SELECT Count(*) As rowa, member.Ssurname, Sum(Case When ((member.status = '1')) Then 1 Else 0 End) As Status11 From member Group By member.Ssurname Order By rowa Desc";
arr[4] = "DROP TABLE IF EXISTS `q_mem_hno` ; create table q_mem_hno as select member.Hno, member.Moo, member.tambol, COUNT( member.Hno ) AS cntHno, COUNT(DISTINCT member.Ssurname) as NoSur FROM member GROUP BY member.Hno, member.Moo, member.tambol ORDER BY cntHno DESC ";
arr[5] = "DROP TABLE IF EXISTS `q_pro_ori`; create table q_pro_ori as Select member.provincecode, count(*) As cnt From member Group By member.provincecode Order By cnt Desc ";
arr[6] = "DROP TABLE IF EXISTS `q_am_ori`; create table q_am_ori as Select member.amphurecode, member.provincecode, count(*) As cnt From member Group By member.amphurecode, member.provincecode Order By cnt Desc ";
arr[7] = "DROP TABLE IF EXISTS `Sur_Hno_`; create table Sur_Hno_ as SELECT count( * ) , Ssurname, q_mem_tim.Hno, q_mem_tim.Moo, q_mem_tim.tambol FROM q_mem_tim GROUP BY q_mem_tim.Ssurname, q_mem_tim.Hno, q_mem_tim.Moo, q_mem_tim.tambol ORDER BY count( * ) DESC";
arr[8] = "DROP TABLE IF EXISTS `q_dup_own`; create table q_dup_own as SELECT Count(*) as n ,member.own FROM member GROUP BY member.own order by n DESC ";
// arr[9] = "drop table if exists q_mem_birth; create table q_mem_birth as SELECT member.idmember, member.own, member.provincecode, province.PROVINCE_NAME, member.amphurecode, amphur.AMPHUR_NAME, member.Sname, member.Ssurname, member.Hno, member.Moo, member.Sex, member.tambol, member.dateofbirth, member.migratedate, member.fathercode , member.mathercode, Year( Current_Date( ) ) - Year( member.dateofbirth ) AS y, DATEDIFF('2011-08-01',(migratedate)) AS d ,member.inputstaf FROM member LEFT JOIN amphur ON ( member.amphurecode = amphur.AMPHUR_CODE ) LEFT JOIN province ON member.provincecode = province.PROVINCE_CODE WHERE DAYOFYEAR(member.dateofbirth)-DAYOFYEAR(NOW()) < 30 and DAYOFYEAR(member.dateofbirth)-DAYOFYEAR(NOW()) > -1 order by DAYOFYEAR(member.dateofbirth)";
arr[9] = "ALTER TABLE `q_mem_tim` ADD `agec` VARCHAR( 10 ) NULL ";
// arr[10] = "UPDATE q_mem_birth SET agec = CASE WHEN y < 10 THEN 'ด' WHEN y > 10 and y < 20 and Sex='ญ' THEN 'วญ' WHEN y > 10 and y < 20 and Sex='ช' THEN 'วช' ELSE 'ผญ' END";
arr[10] = "drop table if exists q_mem_birth; create table q_mem_birth as SELECT q_mem_tim.idmember,q_mem_tim.own,q_mem_tim.PROVINCE_NAME,q_mem_tim.AMPHUR_NAME,q_mem_tim.novote,q_mem_tim.Sname,q_mem_tim.Ssurname,q_mem_tim.Hno,q_mem_tim.Moo,q_mem_tim.Sex,q_mem_tim.tambol,q_mem_tim.dateofbirth,q_mem_tim.migratedate,q_mem_tim.y,q_mem_tim.d,q_mem_tim.agec FROM q_mem_tim where q_mem_tim.dateofbirth is not null and q_mem_tim.dateofbirth != '00000000' and day(q_mem_tim.dateofbirth) != '00' and day(q_mem_tim.dateofbirth) > 0 and day(q_mem_tim.dateofbirth) < 11 and month(q_mem_tim.dateofbirth) != '00' and month(q_mem_tim.dateofbirth) = #numVal order by tambol,Moo, month(dateofbirth),day(dateofbirth) ";
foreach (string s in arr)
{
Console.WriteLine(s);
MySqlCommand cmdDbase = new MySqlCommand((s), conDatabase);
cmdDbase.CommandTimeout = 500;
cmdDbase.ExecuteNonQuery();
}
conDatabase.Close();
}
}
}
1)Truncate the tables; don't drop them and remake them because when you drop them you have to do the indexes and add the Primary Keys again.
using(var cm = _dbConnection.CreateCommand())
{
cm.CommandText = #"Truncate Table Table";
cm.CommandType = CommandType.Text;
cm.ExecuteNonQuery();
}
2)Don't forget the # symbol; it helps with anything SQL:
using(var cm = _dbConnection.CreateCommand())
{
cm.CommandText = #"Select *
From table
Where Id = #Id";
cm.CommandType = CommandType.Text;
cm.Parameter.AddWithValue("Id", id);
cm.ExecuteNonQuery();
}
I know you're not doing it this way and you're using a string array (just put a foreach loop outside the using statement and replace the cm.CommandText value with the string's value) but with the examples it should help you or at least give you some ideas.
You need to add a MySqlParameter to the command named numVal.

Categories

Resources