Insert and update a datetime into SQL database - c#

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 += ")";

Related

What is wrong with this MySQL query in C#?

I'm trying to insert multiple rows into a table by building a query by iterating through a list. I'm getting errors for my SQL syntax, it looks like this:
string sql = "insert into achievement(Rank,Event,UserId) values ";
string valueSQL = "";
using (command = new MySqlCommand("begin;" +
" insert into profile(Username,TextInfo) values(#username,#textinfo);" +
" set #userid = LAST_INSERT_ID(); " +
sql +
" insert into social(URL,UserId) values(#url,#userid);" +
" COMMIT;", conn))
{
command.Parameters.AddWithValue("username", dto.Username);
command.Parameters.AddWithValue("textinfo", dto.FreeText);
command.Parameters.AddWithValue("url", dto.SocialURL);
for(int i = 0; i < dto.achievementDTOs.Count; i++)
{
valueSQL += /*(valueSQL == "" ? "": ",") +*/ "(#rank" + i + ",#event" + i + ",#userid)";
command.Parameters.AddWithValue("rank"+i, dto.achievementDTOs[i].Rank);
command.Parameters.AddWithValue("event"+i, dto.achievementDTOs[i].Event);
}
sql += valueSQL;
sql += ";";
command.ExecuteNonQuery();
The end results of building this query should look something like this:
"begin;" +
" insert into profile(Username,TextInfo) values(#username,#textinfo);" +
" set #userid = LAST_INSERT_ID(); " +
" insert into achievement(Rank,Event,UserId) values (#rank0,#event0,#userid) (#rank1,#event1,#userid)" etc. etc. etc. +
" insert into social(URL,UserId) values(#url,#userid);" +
" COMMIT;"
Ive seen the problem
Your code:
string sql = "insert into achievement(Rank,Event,UserId) values ";
string valueSQL = "";
using (command = new MySqlCommand("begin;" +
" insert into profile(Username,TextInfo) values(#username,#textinfo);" +
" set #userid = LAST_INSERT_ID(); " +
sql +
" insert into social(URL,UserId) values(#url,#userid);" +
" COMMIT;", conn)
So. look carefully, at the sql string.. you didnt add the values to insert.. the syntax error would have pointed this out. I havent tried adding multiple rows in one insert like that, but, if that is valid, form the sql as you have but only after working out the sql variale.. eg more like
string sql = "insert into achievement(Rank,Event,UserId) values ";
string valueSQL = "";
for(int i = 0; i < dto.achievementDTOs.Count; i++)
{
valueSQL += /*(valueSQL == "" ? "": ",") +*/ "(#rank" + i + ",#event" + i + ",#userid)";
command.Parameters.AddWithValue("rank"+i, dto.achievementDTOs[i].Rank);
command.Parameters.AddWithValue("event"+i, dto.achievementDTOs[i].Event);
}
sql += valueSQL;
sql += ";";
using (command = new MySqlCommand("begin;" +
" insert into profile(Username,TextInfo) values(#username,#textinfo);" +
" set #userid = LAST_INSERT_ID(); " +
sql
" insert into social(URL,UserId) values(#url,#userid);" +
" COMMIT;", conn)

Custom function for insert/update SQL with C#

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

How to run Method that depends on Combobox value and called through Combobox SelectionChanged event

I have multiple TextBoxes for each field on my datagrid, which multi-filters my data based on these textbox entries. This filtering is handled by a method called ApplyFilter() which works fine.
Datagrid is populated by queries from MS SQL Server 2008 which runs on our server on the network. By default datagrid selects top 100 results to speed up things. I have a combobox called "cboSelectTop" which is populated by numbers 10, 100, 1000, ALL for user to increase/decrease the results from query.
Applyfilter() returns query based on this combobox value. When I call Applyfilter() method from TextBox's TextChanged event, filtering runs as intended. But if I call ApplyFilter() from Combobox SelectionChanged event, I get System.NullReferenceException at if(!string.IsNullOrEmpty(txtSupplier.Text)) which says
Object reference not set to an instance of an object. txtSupplier was
Null
Question is: What is the workaround to run Applyfilter(), that depends on combobox value, to function both from TextBox TextChanged event and Combobox SelectionChanged event?
The important part of my ApplyFilter() method is:
private void ApplyFilter()
{
string sConn = #"Data Source=;Initial Catalog=;
User ID=;Password=;";
using (SqlConnection sc = new SqlConnection(sConn))
{
sc.Open();
if (!string.IsNullOrEmpty(txtSupplier.Text))
{
sql1 = "CompanyName like '" + txtSupplier.Text + "%'and ";
}
else
{
sql1 = "";
}
.
.
.
if (!string.IsNullOrEmpty(txtPrice.Text))
{
sql17 = "Price like '" + txtPrice.Text + "%'and ";
}
else
{
sql17 = "";
}
if (cboSelectTop.Text == "ALL")
{
sql = "Select * from Priceview Where " + sql1 + sql2 + sql3 + sql4 + sql5 + sql6 + sql7 + sql8 + sql9 + sql10 + sql11 + sql12 + sql13 + sql14 + sql15 + sql16 + sql17;
}
else
{
sql = "Select top " + cboSelectTop.Text + " * from Priceview Where " + sql1 + sql2 + sql3 + sql4 + sql5 + sql6 + sql7 + sql8 + sql9 + sql10 + sql11 + sql12 + sql13 + sql14 + sql15 + sql16 + sql17;
}
if (sql.Substring(sql.Length - 4) == "and ")
{
sql = sql.Remove(sql.Length - 4, 4);
}
else if (sql.Substring(sql.Length - 4) == "ere ")
{
sql = sql.Remove(sql.Length - 7, 7);
}
else
{
if (cboSelectTop.Text == "ALL")
{
sql = "Select * from Priceview";
}
else
{
sql = "Select top " + cboSelectTop.Text + " * from Priceview";
}
}
Console.WriteLine(sql);
SqlCommand com = new SqlCommand(sql, sc);
using (SqlDataAdapter adapter = new SqlDataAdapter(com))
{
DataTable dt = new DataTable();
adapter.Fill(dt);
DgPrices.ItemsSource = dt.DefaultView;
}
}
}
Any clue to start with is appreciated.
Simply check if txtSupplier and all other controls have been initialized (!= null) before you try to access them or any their properties in your method:
private void ApplyFilter()
{
string sConn = #"Data Source=;Initial Catalog=;
User ID=;Password=;";
using (SqlConnection sc = new SqlConnection(sConn))
{
sc.Open();
if (txtSupplier != null && !string.IsNullOrEmpty(txtSupplier.Text))
{
sql1 = "CompanyName like '" + txtSupplier.Text + "%'and ";
}
else
{
sql1 = "";
}
.
.
.
if (txtPrice != null && !string.IsNullOrEmpty(txtPrice.Text))
{
sql17 = "Price like '" + txtPrice.Text + "%'and ";
}
else
{
sql17 = "";
}
if (cboSelectTop == null)
return;
if (cboSelectTop.Text == "ALL")
...
}
}
The SelectionChanged event for a ComboBox may fire initially before all controls have been initialized and that's why you get a NullReferenceException.

C# File list in reverse order. (Without Using Linq)

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

how to create a table having spaces between the words?

I am trying to create a table using code.
Here is my code.
private void btnOK_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Open) { con.Close(); }
con.Open();
string s = "CREATE TABLE "+"" + rchtxtFieldCode.Text + " "+ " (" + rchFieldTitle.Text + " " + combDataType.Text + "" + ")";
SqlCommand cmd = new SqlCommand(s, con);
if (cmd.ExecuteNonQuery() >= 1)
{
MessageBox.Show("created");
}
con.Close();
}
It is creating the table if the table name has single word.. It is showing exception if there is space between the words(eg: Sales Info)
If this is for SQL Server you use square brackets:
string s = "CREATE TABLE ["+"" + rchtxtFieldCode.Text + "] "+ " ([" + rchFieldTitle.Text + "] " + combDataType.Text + "" + ")";
In fact you should always use square brackets to stop these kind of errors happening.
Also ensure you are sanitising your strings otherwise you might have SQL injection issues.
Just add Box braces:
string s = "CREATE TABLE ["+"" + rchtxtFieldCode.Text + "] "+ " (" + rchFieldTitle.Text + " " + combDataType.Text + "" + ")";
//^_______________________________^
Do not use spaces in table or field names.In this, Try to change query with Square brackets i.e.
For example ,
sqlString = "CREATE TABLE [All Students]"
use this code, i think it will give you the desire output.
private void btnOK_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Open) { con.Close(); }
con.Open();
string s = "CREATE TABLE '"+rchtxtFieldCode.Text + "'(" +"'"+rchFieldTitle.Text +"'" + combDataType.Text + "" + ")";
SqlCommand cmd = new SqlCommand(s, con);
if (cmd.ExecuteNonQuery() >= 1)
{
MessageBox.Show("created");
}
con.Close();
}

Categories