sorry if this argument was already treated but I didn't find anything.
I'm writing a program that have many insert/update query, my problem is that I don't like so much writing query with String.Format method like:
query = "INSERT INTO righe_comanda (id_originale, quantita, nome, prezzo, id_comanda,";
query += "variazionipositive,variazioninegative,opzioneselezionata,evaso, data_evasione, user_evasione) VALUES";
query += "({0},{1},'{2}','{3}',{4},'{5}','{6}','{7}',{8},'{9}','{10}');";
query = String.Format(query, id_originale, quantita, nome, prezzo, ID_Comanda, VariazioniPositive, VariazioniNegative, OpzioneSelezionata, Evaso, DataEvasione, UserEvasione);
It is easy to make an error of number of arguments, with ' ', and so on. So I wrote a function that create the query automatically. See:
public static string QueryFormat(string nometabella, string modalita, Dictionary<string, string> parametri, string where_column = null, string where_value = null)
{
string query = "";
if (modalita == "INSERT")
{
query += "INSERT INTO " + nometabella + " (";
foreach (var item in parametri)
{
query += item.Key + ", ";
}
query = query.Substring(0, query.Length - 2);
query += ") VALUES (";
foreach (var item in parametri)
{
query += GestisciValore(item.Value) + ", ";
}
query = query.Substring(0, query.Length - 2);
query += ")";
}
else if (modalita == "UPDATE")
{
query += "UPDATE " + nometabella + " SET ";
foreach (var item in parametri)
{
query += item.Key + " = " + GestisciValore(item.Value) + ", ";
}
query = query.Substring(0, query.Length - 2);
query += " WHERE " + where_column + " = " + GestisciValore(where_value);
}
return query;
}
private static string GestisciValore(string valore)
{
int n;
if (int.TryParse(valore, out n))
return valore;
else
return "'" + valore + "'";
}
What do you think about this? There is any alternative?
Regards
Related
private static IEnumerable<string> getExtrato(string query)
{
using (var cn = new SqlConnection("Data Source=MAD-PC-023\\SQLEXPRESS;Database=bank;Trusted_Connection=True;"))
{
cn.Open();
using (var cmd = new SqlCommand() { Connection = cn, CommandText = query })
{
var reader = cmd.ExecuteReader();
var result = new List<string>();
while (reader.Read() == true && result.Count <= 9 )
{
if (reader.GetString(1) == "0")
{ //+ "ficando assim com: " + reader.GetDecimal(3)
result.Add("\n O cartão nº " + reader.GetString(0) + " levantou: " + reader.GetString(2) + " euros, " + " às: " + reader.GetDateTime(3));
}
else
{
result.Add("\n O cartão nº " + reader.GetString(0) + " depositou: " + reader.GetString(1) + " euros, " + " às: " + reader.GetDateTime(3));
}
}
return result;
}
}
}
private static IEnumerable<string> extratoOperacao(string numeroCartao)
{
return getExtrato($#"SELECT CardNumber, Deposit, Withdraw, DataHora FROM MoveInfo WHERE CardNumber = '{numeroCartao}'");
}
As I have is presenting me only the first 10 lines, but I need the last 10 by normal order, how do I do that?
If anyone can help me, I'd be grateful
private static IEnumerable<string> getExtrato(string query)
{
using (var cn = new SqlConnection("Data Source=MAD-PC-023\\SQLEXPRESS;Database=bank;Trusted_Connection=True;"))
{
cn.Open();
using (var cmd = new SqlCommand() { Connection = cn, CommandText = query })
{
var reader = cmd.ExecuteReader();
var result = new List<string>();
// Let's remove unused conditions
while (reader.Read())
{
if (reader.GetString(1) == "0")
{
result.Add("\n O cartão nº " + reader.GetString(0) + " levantou: " + reader.GetString(2) + " euros, " + " às: " + reader.GetDateTime(3));
}
else
{
result.Add("\n O cartão nº " + reader.GetString(0) + " depositou: " + reader.GetString(1) + " euros, " + " às: " + reader.GetDateTime(3));
}
}
// HERE IS THE MAGIC
return result.TakeLast(10);
}
}
}
If you use an ORDER BY in the query you can make sure which records are returned, and you can use TOP to restrict the quantity of records returned, so something like
return getExtrato($#"SELECT TOP 10 [CardNumber], [Deposit], [Withdraw], [DataHora], [Id] FROM [MoveInfo] WHERE [CardNumber] = '{numeroCartao}' ORDER BY [Id] DESC");
will return the desired records, and then you just need to read all of them and reverse the result in your code (there are other possibilities, but that might be simplest for now).
I build the following SQL query dynamically:
StringBuilder query = new StringBuilder();
StringBuilder query2 = new StringBuilder();
if (ComboRuleType.Text.Equals("Standard"))
{
query.Append("select * from [dbo].[" + ComboRuleTableName.Text + "]" + " WHERE" + "\n");
query.Append("(" + "\n");
for (int i = 0; i < dgvUpdateCriteria.RowCount; i++)
{
DataGridViewRow row = dgvUpdateCriteria.Rows[i];
if (i != 0)
{
query.Append(row.Cells[1].Value.ToString() + " " + row.Cells[3].Value.ToString() + " ");
}
else
{
query.Append(row.Cells[3].Value.ToString() + " ");
}
if (row.Cells[4].Value.ToString().Equals("Contains"))
{
query.Append("like " + "'%" + row.Cells[5].Value.ToString() + "%'" + "\n");
}
else if (row.Cells[4].Value.ToString().Equals("Equals"))
{
query.Append("= " + "'" + row.Cells[5].Value.ToString() + "'" + "\n");
}
else if (row.Cells[4].Value.ToString().Equals("StartsWith"))
{
query.Append("like " + "'" + row.Cells[5].Value.ToString() + "%'" + "\n");
}
else if (row.Cells[4].Value.ToString().Equals("EndsWith"))
{
query.Append("like " + "'%" + row.Cells[5].Value.ToString() + "'" + "\n");
}
}
query.Append(")" + "\n");
return query.ToString();
}
After converting the above to Entity SQL, it looks like:
StringBuilder query = new StringBuilder();
StringBuilder query2 = new StringBuilder();
if (ComboRuleType.Text.Equals("Standard"))
{
query.Append("select value q1 from ");
query.Append(ComboRuleTableName.Text);
query.Append("s");
query.Append(" as q1 where " + "\n");
for (int i = 0; i < dgvUpdateCriteria.RowCount; i++)
{
DataGridViewRow row = dgvUpdateCriteria.Rows[i];
if (i != 0)
{
if (row.Cells[1].Value.ToString().Equals("AND"))
{
query.Append("&&" + " " + "q1." + row.Cells[3].Value.ToString());
}
else
{
query.Append("||" + " " + "q1." + row.Cells[3].Value.ToString());
}
}
else
{
query.Append("q1." + row.Cells[3].Value.ToString());
}
if (row.Cells[4].Value.ToString().Equals("Contains"))
{
query.Append(" LIKE (" + "'%" + row.Cells[5].Value.ToString() + "%'" + ")" + "\n");
}
else if (row.Cells[4].Value.ToString().Equals("Equals"))
{
query.Append(" == (" + "'" + row.Cells[5].Value.ToString() + "'" + ")" + "\n");
}
else if (row.Cells[4].Value.ToString().Equals("StartsWith"))
{
query.Append(" LIKE (" + "'" + row.Cells[5].Value.ToString() + "%'" + ")" + "\n");
}
else if (row.Cells[4].Value.ToString().Equals("EndsWith"))
{
query.Append(" LIKE (" + "'%" + row.Cells[5].Value.ToString() + "'" + ")" + "\n");
}
}
return query.ToString();
}
I construct another SQL query that contains INNER JOIN and I have looked EVERYWHERE but cannot find the equivalent translation of that SQL query to an Entity SQL query. I would really appreciate if you can help me out. The dynamic SQL query with INNER JOIN is as follows:
query.Append("SELECT * ");
query.Append("FROM [dbo].[membership] mm \n");
query.Append("INNER JOIN [dbo].[" + ComboRuleTableName.Text + "] xx \n");
query.Append("ON (mm.m_" + ComboRuleTableName.Text + "_id = xx.id) \n");
query.Append("WHERE xx.id IN ( \n");
query.Append("SELECT id from [dbo].[" + ComboRuleTableName.Text + "] \n");
query.Append("WHERE \n");
query.Append("mm.platform_name = '" + ComboRulePlatformName.Text + "' AND (\n");
for (int i = 0; i < dgvUpdateCriteria.RowCount; i++)
{
DataGridViewRow row = dgvUpdateCriteria.Rows[i];
if (i != 0)
{
query2.Append(row.Cells[1].Value.ToString() + " " + row.Cells[3].Value.ToString() + " ");
}
else
{
query2.Append(row.Cells[3].Value.ToString() + " ");
}
if (row.Cells[4].Value.ToString().Equals("Contains"))
{
query2.Append("like " + "'%" + row.Cells[5].Value.ToString() + "%'" + "\n");
}
else if (row.Cells[4].Value.ToString().Equals("Equals"))
{
query2.Append("= " + "'" + row.Cells[5].Value.ToString() + "'" + "\n");
}
else if (row.Cells[4].Value.ToString().Equals("StartsWith"))
{
query2.Append("like " + "'" + row.Cells[5].Value.ToString() + "%'" + "\n");
}
else if (row.Cells[4].Value.ToString().Equals("EndsWith"))
{
query2.Append("like " + "'%" + row.Cells[5].Value.ToString() + "'" + "\n");
}
else
{
query2.Append(" \n");
}
}
query2.Append("))\n");
return query.Append(query2).ToString();
I NEED it to be in a string format. I later convert it from string to query format. I just do not know how the INNER JOIN syntax works with Entity queries.
Thank you.
Edit 1:
Here is how I convert that Query into Entity Framework Object Query:
string query = EntityPreview(); //EntityPreview() is the method that gives me Raw Entity SQL Query
var objctx = (context as IObjectContextAdapter).ObjectContext;
if (ComboRuleTableName.Text.Equals("system"))
{
ObjectQuery<system> standardList = objctx.CreateQuery<system>(query);
rulePreviewForm.dataGridViewCriteriaRulePreview.DataSource = standardList;
rulePreviewForm.Show();
}
One of the greatest things about EntityFramework is it builds SQL for you and allows you to manipulate objects instead of SQL. There are other libraries like Dapper that are quicker when using straight SQL if you have a choice. If you have to use EntityFramework, you would be better off writing Linq.
When using Linq instead of SQL, you can still build Dynamic queries using IQueryable. This allows you to build a query without pulling any data from the database up front.
Without knowing much about what you are trying to do with your application, I can only offer a few tips of things to try. In the answer below I am making some assumptions on the naming of how you have your entities set up.
For getting a list of memberships from the membership table, assuming your entity for that table is called Membership:
IQueryable<Membership> memberships = context.Memberships;
That is your
query.Append("SELECT * ");
query.Append("FROM [dbo].[membership] mm \n");
For your filters you will likely want to put them into a List.
From this point on is where the dynamic part of this comes in. If you have a table for your ComboRule named [ComboRuleTable1] and another called [ComboRuleTable2], but you have to query based on input from ComboRuleTableName.Text, you can do something like this.
var filters = new List<string>() { "name1", "name2" };
// Get which table you should join to
switch (ComboRuleTable1)
{
// Join to tables and get filtered data
case "ComboRuleTable1":
memberships = memberships.ComboRuleTable1.Where(x => filters.Contains(x.PlatFormName));
break;
case "ComboRuleTable2":
memberships = memberships.ComboRuleTable2.Where(x => filters.Contains(x.PlatFormName));
break;
default:
break;
}
// This pulls the data from the database
var result = memberships.ToList();
Some of this will vary on how your EntityFramework is set up.
I hope this helps.
I am currently working on accessing a database using OleDB and I am having issue with string replacement of OleDBParameter.
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM " + tablename + " WHERE ID = #ID ;";
cmd.Parameters.AddWithValue("#ID", testslist.number + "_" + testcase.name + "_" + testcase.config);
OleDbDataReader reader = cmd.ExecuteReader();
RecordExists = reader.HasRows;
reader.Close();
if (RecordExists)
{
string updatestring = null;
foreach (KeyValuePair<string, string> kv in dictionary)
updatestring = updatestring + kv.Key + " = '#val" + kv.Key + "',";
cmd.CommandText = "UPDATE " + tablename + " SET " + updatestring.Remove(updatestring.Length - 1) + " WHERE ID = #ID;";
foreach(KeyValuePair<string,string> kv in dictionary)
{
if (kv.Value == null)
cmd.Parameters.AddWithValue("#val" + kv.Key, DBNull.Value);
else
cmd.Parameters.AddWithValue("#val" + kv.Key, kv.Value);
}
cmd.ExecuteNonQuery();
}
else
{
string insertstring = "ID,";
string valuestring = "#ID,";
foreach(KeyValuePair<string,string>kv in dictionary)
{
insertstring = insertstring + kv.Key + ",";
valuestring = valuestring + "#var" + kv.Key + ",";
// valuestring = valuestring + "'"+ kv.Value+ "',";
}
cmd.CommandText = "INSERT INTO " + tablename + " (" + insertstring.Remove(insertstring.Length - 1) + ") VALUES(" + valuestring.Remove(valuestring.Length - 1) + ");";
foreach (KeyValuePair<string, string> kv in dictionary)
{
if (kv.Value == null)
cmd.Parameters.AddWithValue("#val" + kv.Key, DBNull.Value);
else
cmd.Parameters.AddWithValue("#val" + kv.Key, kv.Value);
}
cmd.ExecuteNonQuery();
}
For whatever reason, only the #ID is getting replaced correctly in my database. After running the code, the ID is replaced correctly in my database, but every other field values are #var[nameofthekey] (#varTestCase for example) . I really don't know where to look anymore especially since one the parameter gets replaced properly in the database, but not the other.
Thank you for your help!
edit: I forgot to mention, I am working with an access database (accdb)
private void ButtonOk_Click(object sender, EventArgs e)
{
if (txtWedstrijdSchemaID.Text == "")
{
//Insert
string SQL;
SQL = "Insert into Wedstrijdschema (Team1, Team2, Datum)";
SQL += " values (";
SQL += "" + txtTeam1.Text + ",";
SQL += "" + txtTeam2.Text + ",";
SQL += "" + Convert.ToDateTime(txtDatum.Text) + "";
SQL += ")";
clDatabase.ExecuteCommand(SQL);
vulLv();
}
else
{
//Update
string SQL;
SQL = "Update Wedstrijdschema SET ";
SQL += "Team1 = " + txtTeam1.Text + ",";
SQL += "Team2 = " + txtTeam2.Text + ",";
SQL += "Datum = " + Convert.ToDateTime(txtDatum.Text) + "";
SQL += " where SchemaId = " + zoek;
clDatabase.ExecuteCommand(SQL);
vulLv();
}
txtDatum.Enabled = txtTeam2.Enabled = txtTeam1.Enabled = false;
}
That is what I currently have, because of a trycatch it won't crash when I try, if I comment the txtDatum.Text out on the //insert and //upload it works (but obviously enters NULL for Datum in the Database) does anyone perhaps see where I'm going wrong?
EDIT: About the use of parameters, we need to use a threetier system where all SQL goes through a class which is the only one allowed to do anything with the database, this is how the command is executed:
public static bool ExecuteCommand(string SQLInstructie)
{
bool retour = true;
SqlConnection Conn = new SqlConnection(clStam.Connstr);
SqlCommand Cmd = new SqlCommand(SQLInstructie, Conn);
try
{
Cmd.Connection.Open();
Cmd.ExecuteNonQuery();
}
catch
{
retour = false;
}
finally
{
Conn.Close();
}
return retour;
}
This works!! Thanks a lot for the help:
private void ButtonOk_Click(object sender, EventArgs e)
{
if (txtWedstrijdSchemaID.Text == "")
{
//Insert
string SQL;
SQL = "Insert into Wedstrijdschema (Team1, Team2, Datum)";
SQL += " values (";
SQL += "" + txtTeam1.Text + ",";
SQL += "" + txtTeam2.Text + ",";
SQL += "'" + Convert.ToDateTime(txtDatum.Text) + "'";
SQL += ")";
Debug.WriteLine(SQL);
clDatabase.ExecuteCommand(SQL);
vulLv();
}
else
{
//Update
string SQL;
SQL = "Update Wedstrijdschema SET ";
SQL += "Team1 = " + txtTeam1.Text + ",";
SQL += "Team2 = " + txtTeam2.Text + ",";
SQL += "Datum = '" + Convert.ToDateTime(txtDatum.Text) + "'";
SQL += " where SchemaId = " + zoek;
clDatabase.ExecuteCommand(SQL);
vulLv();
}
txtDatum.Enabled = txtTeam2.Enabled = txtTeam1.Enabled = false;
}
EDIT: I'll promise to use parameterized SQL from now on!
You are missing a command , from the INSERT and UPDATE statement.
The syntax to insert data into the database is:
INSERT INTO Table
(Column1, Column2, Column3)
VALUES
('Value 1', 'Value 2', 'Value3')
Aside that, you are vulnerable to SQL injection, use SQL paramerterised queries to prevent this.
I would first start off by using a SqlCommand object.
SqlCommand cmd = new SqlCommand("INSERT INTO Wedstrijdschema (Team1, Team2, Datum) VALUES (#V1, #V2, #V3");
cmd.Parameters.AddWithValue("#V1", txtTeam1.Text);
cmd.Parameters.AddWithValue("#V2", txtTeam2.Text);
cmd.Parameters.AddWithValue("#V3", Convert.ToDateTime(txtDatum.Text));
And then execute it using cmd.ExecuteNonQuery();
As an additional note I would also ensure that the value in txtDatum is converted correctly to the desired date format.
remove single quotes from datetime column. also you missed column to add in insert statement
private void ButtonOk_Click(object sender, EventArgs e)
{
if (txtWedstrijdSchemaID.Text == "")
{
//Insert
string SQL;
SQL = "Insert into Wedstrijdschema (Team1, Team2,**Datum**)";
SQL += " values (";
SQL += "" + txtTeam1.Text + ",";
SQL += "" + txtTeam2.Text + "";
SQL += "" + Convert.ToDateTime(txtDatum.Text) + "";
SQL += ")";
clDatabase.ExecuteCommand(SQL);
vulLv();
}
else
{
//Update
string SQL;
SQL = "Update Wedstrijdschema SET ";
SQL += "Team1 = " + txtTeam1.Text + ",";
SQL += "Team2 = " + txtTeam2.Text + "";
SQL += "Datum = " + Convert.ToDateTime(txtDatum.Text) + "";
SQL += " where SchemaId = " + zoek;
clDatabase.ExecuteCommand(SQL);
vulLv();
}
txtDatum.Enabled = txtTeam2.Enabled = txtTeam1.Enabled = false;
}
Always use parameterized queries.string concatenations make a way to sql injection
private void ButtonOk_Click(object sender, EventArgs e)
{
if (txtWedstrijdSchemaID.Text == "")
{
SqlCommand cmd = new SqlCommand("Insert into Wedstrijdschema (Team1, Team2, Datum) values (#Team1,#Team2,#datetime)");
cmd.Parameters.AddWithValue("#Team1",txtTeam1.Text
cmd.Parameters.AddWithValue("#Team2",txtTeam2.Text
cmd.Parameters.AddWithValue("#datetime",Convert.ToDateTime(txtDatum.Text)
clDatabase.ExecuteCommand(SQL);
vulLv();
}
else
{
SqlCommand cmd = new SqlCommand("Update Wedstrijdschema SET Team1=#team1,Team2=#team2,Datum =#Datum where SchemaId=#SchemaId");
cmd.Parameters.AddWithValue("#team1",txtTeam1.Text );
cmd.Parameters.AddWithValue("#team2",txtTeam2.Text);
cmd.Parameters.AddWithValue("#Datum ",Convert.ToDateTime(txtDatum.Text);
cmd.Parameters.AddWithValue("#SchemaId",zoek);
clDatabase.ExecuteCommand(SQL);
vulLv();
}
txtDatum.Enabled = txtTeam2.Enabled = txtTeam1.Enabled = false;
}
Use ToString to format your date in an acceptable format (and enclose in quotes as it's being passed as a string):
string SQL;
SQL = "Insert into Wedstrijdschema (Team1, Team2, Datum)";
SQL += " values (";
SQL += "" + txtTeam1.Text + ",";
SQL += "" + txtTeam2.Text + ",";
SQL += "'" + Convert.ToDateTime(txtDatum.Text).ToString("yyyy-MM-dd HH:mm:ss") + "'";
SQL += ")";
I have searched around and it seem's the only answer I can get is to do with LINQ, which I don't have available on my visual stuido 2005.
I am building a program that reads files and imports them into a database, the way it's set up at the moment, it reads the very latest date it finds.
I want to read the earliest file first.
Is there any way around this?
Here is my code
private string mDirectory; // this will hold the directory path you are working on
private string[] mFiles; // this will hold all files in the selected directory
private void ReadData()
{
this.toolStripStatusLabel1.Text = "Preparing To Read Data";
this.Refresh();
string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};;persist security info=false;Extended Properties=dBase IV", mDirectory);
this.richTextBox1.Text = connectionString;
try
{
foreach (string file in mFiles)
{
mDirectory = #"C:\USERS\DESKTOP\Test Pressure\";
mFiles = System.IO.Directory.GetFiles(mDirectory, "*(WIDE).DBF");
DateTime dt = File.GetLastWriteTime(file);
string newdate = dt.ToString("yyyy-MM-dd HH:mm:ss");
DateTime DBTIME = new DateTime(2014, 01, 01, 00, 00, 00);
string date = String.Format("{0:yyyy-MM-dd HH:mm:ss}", DBTIME);
//this.richTextBox1.Text = date;
if (dt > DBTIME)
{
StringBuilder sb = new StringBuilder(300);
int n = GetShortPathName(file, sb, 300);
if (n == 0) // check for errors
MessageBox.Show(Marshal.GetLastWin32Error().ToString());
else
{ }
string filenameWithoutPath1 = System.IO.Path.GetFileName(sb.ToString());
string queryString = string.Format("SELECT * FROM [" + "{0}]", filenameWithoutPath1);
this.richTextBox1.Text = queryString;
string where = " WHERE BAR > 20.0";
string myquery = queryString + where;
// this.richTextBox1.Text = myquery;
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(myquery, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (reader.IsDBNull(1))
{
this.richTextBox1.Text = "Null";
}
else
{
string Query = "REPLACE INTO hp42mis.hydrodata (FILEMOD, DOEYMD,TIMEHMS,DATETIMEM,MARKER,CONTRACT_CODE,STS_00" +
",PIPE,PIPE_NO,STS_01,MAX_PRESB,STS_02,MIN_PRESSB,STS_03,TESTP_BAR,STS_04,five,STS_05,six,STS_06,seven,STS_07," +
"eight,STS_08,nine,STS_09) values ('" + newdate.ToString() + "',";
Query += "'" + Convert.ToDateTime(reader["Date"]).ToString("yyyy-MM-dd") + "'";
Query += ",'" + reader.GetValue(1).ToString() + "'";
Query += ",'" + Convert.ToDateTime(reader["Date"]).ToString("yyyy-MM-dd") + " " + reader.GetValue(1).ToString() + "'";
Query += ",'" + reader.GetValue(2).ToString() + "'";
Query += ",'" + reader.GetValue(3).ToString() + "'";
Query += ",'" + reader.GetValue(4).ToString() + "'";
Query += ",'" + reader.GetValue(5).ToString() + "'";
Query += ",'" + reader.GetValue(3).ToString() + "" + reader.GetValue(5).ToString() + "'";
Query += ",'" + reader.GetValue(6).ToString() + "'";
Query += ",'" + reader.GetValue(7).ToString() + "'";
Query += ",'" + reader.GetValue(8).ToString() + "'";
Query += ",'" + reader.GetValue(9).ToString() + "'";
Query += ",'" + reader.GetValue(10).ToString() + "'";
Query += ",'" + reader.GetValue(11).ToString() + "'";
Query += ",'" + reader.GetValue(12).ToString() + "'";
Query += ",'" + reader.GetValue(13).ToString() + "'";
Query += ",'" + reader.GetValue(14).ToString() + "'";
Query += ",'" + reader.GetValue(15).ToString() + "'";
Query += ",'" + reader.GetValue(16).ToString() + "'";
Query += ",'" + reader.GetValue(17).ToString() + "'";
Query += ",'" + reader.GetValue(18).ToString() + "'";
Query += ",'" + reader.GetValue(19).ToString() + "'";
Query += ",'" + reader.GetValue(20).ToString() + "'";
Query += ",'" + reader.GetValue(21).ToString() + "'";
Query += ",'" + reader.GetValue(22).ToString() + "'";
Query += ")";
MySqlCommand cmd = new MySqlCommand(Query, conne);
this.richTextBox1.Text = Query;
this.Refresh();
int res = 0;
try
{
res = cmd.ExecuteNonQuery();
}
catch (MySqlException Myex)
{
MessageBox.Show(Myex.Message);
}
rowcounter++;
this.rowcount.Text = rowcounter.ToString();
this.Refresh();
conne.Dispose();
conne.Close();
}
}
reader.Close();
connection.Close();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I found an easier way how to sort the array of files...
mFiles = System.IO.Directory.GetFiles(mDirectory, "*(WIDE).DBF");
Array.Sort(mFiles);
If you want to walk over your mFiles array based on each file's last write time, see Sort List using string without Linq:
private IList<string> GetOrderedFiles(string[] files)
{
var fileList = new List<string>(files);
Comparison<string> compare = delegate(string file1, string file2)
{
DateTime file1Time = File.GetLastWriteTime(file1);
DateTime file2Time = File.GetLastWriteTime(file2);
return file1Time.CompareTo(file2Time);
};
fileList.Sort(compare);
return fileList;
}
Usage:
var sortedFiles = GetOrderedFiles(mFiles);
foreach (string file in sortedFiles)
{
}
As others have said, that code needs reformatting and probably isn't even correct (e.g. you're setting mFiles within a loop iterating through mFiles).
However, maybe this will help?
Sorting Directory.GetFiles()
The key is using FileInfo items rather than just GetFiles().
You can do this :
public class ReverseComparer : IComparer<FileSystemInfo>
{
public int Compare(FileSystemInfo x, FileSystemInfo y)
{
return x.CreationTime.CompareTo(y);
}
}
DirectoryInfo di = new DirectoryInfo("C:\\...");
FileSystemInfo[] files = di.GetFileSystemInfos();
Array.Sort(files, new ReverseComparer());