Insert nullable int in c# using mysql - c#

I have a table in mysql for users. Sometime user has a boss and sometime it don't.
So boss data type in nullable int(it is a foreign key, that's why nullable INT).
I was using following code and it was causing problem when boss value is null, producing following error "Incorrect integer value: '' for column 'boss_id' at row 1"
string query = " INSERT INTO " + databasename + ".system_user (" +
"`boss_id`, " +
"`name`, " +
"`user_name`, " +
"`password_2`, " +
"`designation`," +
"`digital_signature`," +
"`functional_role`," +
"`group_2`) " +
"VALUES ('" +
systemuser.Boss + "', '" +
systemuser.Name + "','" +
systemuser.UserName + "', '" +
systemuser.Password + "', '" +
systemuser.Designation + "', '" +
systemuser.DigitalSignature + "', '" +
systemuser.FunctionalRole + "', '" +
systemuser.Group + "');";
MySqlConnection conDataBase = new MySqlConnection(myconnection);
MySqlCommand cmdDataBase = new MySqlCommand(query, conDataBase);
MySqlDataReader myreader;
try
{
conDataBase.Open();
myreader = cmdDataBase.ExecuteReader();
conDataBase.Close();
return true;
}
catch (Exception ex)
{
conDataBase.Close();
MessageBox.Show(ex.Message);
return false;
}
So, i changed the code for string query as follow:
string query = "";
if(systemuser.Boss!=null)
{
query = " INSERT INTO " + databasename + ".system_user (" +
"`boss_id`, " +
"`name`, " +
"`user_name`, " +
"`password_2`, " +
"`designation`," +
"`digital_signature`," +
"`functional_role`," +
"`group_2`) " +
"VALUES ('" +
systemuser.Boss + "', '" +
systemuser.Name + "','" +
systemuser.UserName + "', '" +
systemuser.Password + "', '" +
systemuser.Designation + "', '" +
systemuser.DigitalSignature + "', '" +
systemuser.FunctionalRole + "', '" +
systemuser.Group + "');";
}
else
{
query = " INSERT INTO " + databasename + ".system_user (" +
"`name`, " +
"`user_name`, " +
"`password_2`, " +
"`designation`," +
"`digital_signature`," +
"`functional_role`," +
"`group_2`) " +
"VALUES ('" +
systemuser.Name + "','" +
systemuser.UserName + "', '" +
systemuser.Password + "', '" +
systemuser.Designation + "', '" +
systemuser.DigitalSignature + "', '" +
systemuser.FunctionalRole + "', '" +
systemuser.Group + "');";
}
It worked because, Mysql by default put null at the skipped values.
Now according to my scenario, I have to update boss_id from int to null and sometime from null to int. But my query always skip if value is null. Can you please help me in changing the insert statement in such a way that it would insert null value in boos(if its null) and don't just skip it.

Firstly, you should use parameters, it gives you a clean code and avoid injection.
You can use parameters like this:
string query = string.Format("INSERT INTO {0}.system_user (`boss_id`, `name`, `user_name`, `password_2`, `designation`, `digital_signature`, `functional_role`, `group_2`)" +
"VALUES (#boss_id, #name, #user_name, #password_2, #designation, #digital_signature, #functional_role, #group_2)", databasename);
MySqlConnection conDataBase = new MySqlConnection(myconnection);
MySqlCommand cmdDataBase = new MySqlCommand(query, conDataBase);
cmdDataBase.Parameters.AddWithValue("#boss_id", systemuser.Boss ?? (object)DBNull.Value);
cmdDataBase.Parameters.AddWithValue("#name", systemuser.Name);
cmdDataBase.Parameters.AddWithValue("#user_name", systemuser.UserName);
cmdDataBase.Parameters.AddWithValue("#password_2", systemuser.Password);
cmdDataBase.Parameters.AddWithValue("#designation", systemuser.Designation);
cmdDataBase.Parameters.AddWithValue("#digital_signature", systemuser.DigitalSignature);
cmdDataBase.Parameters.AddWithValue("#functional_role", systemuser.FunctionalRole);
cmdDataBase.Parameters.AddWithValue("#group_2", systemuser.Group);
Note "#boss_id", systemuser.Boss ?? (object)DBNull.Value, this is because you can not use null directly in the parameters.
UPDATE:
If you want to update or delete you can use parameters too:
You can write your queries like this:
string query = string.Format("UPDATE {0}.system_user SET `name` = #name WHERE `boss_id` = #boss_id", databasename);
or
string query = string.Format("DELETE FROM {0}.system_user WHERE `boss_id` = #boss_id", databasename);
For datetime columns you can see this question. It has very good answers.

You are encapsulating the value of Systemuser.Boss in single quotes, doesn't this indicate that you are trying to insert a string into an integer column?
string query = #"INSERT INTO {0}.system_user (
`boss_id`,
`name`,
`user_name`,
`password_2`,
`designation`,
`digital_signature`,
`functional_role`,
`group_2`)
VALUES
{1},
'{2}',
'{3}',
'{4}',
'{5}',
'{6}',
'{7}',
'{8}')
";
string formattedQuery = string.Format(query,
databasename, // {0}
Systemuser.Boss, // {1}
Systemuser.Name, // {2}
etc, etc);
EDIT: missed a part where you said 'when it was null'... you need to use:
(Systemuser.Boss ?? "NULL")

Related

How to insert Persian words into a SQL Server database?

I am just wondering how to insert Persian characters into my service-based database?
When I save my data it shows something like '???'.
I have checked such questions like this. But, the solutions were not useful.
private void button1_Click(object sender, EventArgs e)
{
objConnection.Open();
if (ctypeCheckBox.Checked == true)
st = 1;
else if (ctypeCheckBox.Checked == false)
st = 0;
string query = "INSERT INTO LectureTable(Cname, Cid, Ccredit, Csession, Ctype, CstartDate, CendDate, CstartTime, CendTime) VALUES('" + cnameTextBox.Text + "','" + cidTextBox.Text + "','" + ccreditTextBox.Text + "','" + csessionTextBox.Text + "','" + st + "', '" + cstartDateDateTimePicker.MinDate + "', '" + cendDateDateTimePicker.MaxDate + "', '" + cStartTimeBox.Text + "', '" + cEndTimeBox.Text + "')";
SqlDataAdapter SDA = new SqlDataAdapter(query, objConnection);
SDA.SelectCommand.ExecuteNonQuery();
MessageBox.Show("Inserted!");
objConnection.Close();
}
Two things:
Never ever combine your query string with values
"INSERT INTO LectureTable(Cname, Cid, Ccredit, Csession, Ctype, CstartDate, CendDate, CstartTime, CendTime) VALUES('" + cnameTextBox.Text + "','" + cidTextBox.Text + "','" + ccreditTextBox.Text + "','" + csessionTextBox.Text + "','" + st + "', '" + cstartDateDateTimePicker.MinDate + "', '" + cendDateDateTimePicker.MaxDate + "', '" + cStartTimeBox.Text + "', '" + cEndTimeBox.Text + "')";
Should be immediately replaced with
"INSERT INTO LectureTable(Cname, Cid, Ccredit, Csession, Ctype, CstartDate, CendDate, CstartTime, CendTime)
VALUES(#cname, #cid, #ccredit, #csession, #st, #cstartDateDate, #cendDate, #cStartTime, #cEndTimeB)";
and then you should use
SDA.SelectCommand.Parameters.AddWithValue("cname",cnameTextBox.Text);
for all parameters. This will save you from a lot of problems including SQL injection.
In the database your columns should have nvarchar data type.
Good luck
You should use SqlParameter .Giving example of only one parameter.You can add others as same way.
string query = "INSERT INTO LectureTable(Cname) VALUES(#name)";
using(SqlCommand cmd = new SqlCommand(query, SqlConnection))
{
SqlParameter param = new SqlParameter("#name", cnameTextBox.Text);
param.SqlDbType = SqlDbType.String;
cmd.Parameters.Add(param);
.....
}

Error converting data type varchar to numeric in c# program

Please Help me out,This is my database table in sql-server
(empcode varchar(50)
firstname varchar(50)
lastname varchar(50)
gender varchar(50)
address varchar(50)
contactno numeric(18, 0)
bloodgroup varchar(50)
dateofbirth date
country varchar(50)
qid varchar(50)
passportno varchar(50)
passportexpiredate date
designation varchar(50)
doj date
doexpid date
pf_acc_no numeric(18, 0)
agreementstartdate date
agreementenddate date
department varchar(50)
basic_sal numeric(18, 0)
remarks varchar(50)
empimage image)
and I'm Trying to insert my data through c# windows forms but i'm getting error as "Error converting data type varchar to numeric."
Here below is my c# code
private void button2_Click(object sender, EventArgs e)
{
cn.Open();
if (!empid())
{
DialogResult d = new DialogResult();
d = MessageBox.Show("Do You Declare Yourself All The Information Of This Employee Is Correct To Save?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (d == DialogResult.Yes)
{
int i = 0;
SqlCommand cmd = new SqlCommand("INSERT INTO Employee(
empcode,firstname,lastname,gender,address,contactno,bloodgroup,
dateofbirth, country,qid,passportno,passportexpiredate,designation,
doj,doexpid,pf_acc_no, agreementstartdate,agreementenddate,
department,basic_sal,remarks,empimage)
VALUES('" + txtempcode.Text + "','" + txtfrstname.Text + "',
'" + txtlstname.Text + "','" + combogender.Text + "','" +
txtaddr.Text + "','" + txtcont.Text + "','" + txtblodgrp.Text + "', '" +
dob.Value.ToString("yyyy/MM/dd") + "' ,'" + txtcountry.Text + "','" + tqid.Text + "','" +
txtpassportno.Text + "', '" + passexpdate.Value.ToString("yyyy/MM/dd") + "' ,'" +
combodesig.Text + "', '" + doj.Value.ToString("yyyy/MM/dd") + "', '" + doexpqid.Value.ToString("yyyy/MM/dd") + "', '" +
txtqibacc.Text + "', '" + agreestartdate.Value.ToString("yyyy/MM/dd") + "','" + agreeenddate.Value.ToString("yyyy/MM/dd") + "' ,'" + combobranch.Text + "','" + txtnetsalary.Text + "','" + txtremark.Text + "',#empimage) ", cn);
MemoryStream stream = new MemoryStream();
pb1.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] pic = stream.ToArray();
cmd.Parameters.AddWithValue("#empimage", pic);
i = cmd.ExecuteNonQuery();
if (i > 0)
{
MessageBox.Show("Successfully Inserted Employee Record" + i);
}
cn.Close();
showdata();
clear();
}
}
}
public bool empid()
{
using (SqlConnection con = new SqlConnection("Data Source=SAFIYA-PC;Initial Catalog=dbEmployee;User ID=sa;Password=sa$123"))
{
con.Open();
string query = "select empcode from Employee where empcode = '" + txtempcode.Text + "'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
empCode = dr["empcode"].ToString();
if (empCode != "0")
{
MessageBox.Show("Id already Existed Please use Another One!!!!!!");
return false;
}
con.Close();
}
return true;
}
}
Edit: the comment below is quite right, the immediate issue is that you have single quotes around the data you are trying to put in the contactno numeric(18, 0) field which is telling SQL to interpret that value as a varchar.
Change "','" + txtcont.Text + "','" to "'," + txtcont.Text + ",'" (i.e. remove the single quotes either side of the text box value) and do the same for any other numeric fields.
However, as is mentioned in other responses, this general approach of concatenating together a sql command string is not recommended from a security point of view. The preferred option is to use a parametrised query.
Using a parametrised query will also make it easier to deal with any nullable fields, as per this example.
(Edited to correct the answer in response to comment from Steffen)
Why don't you use parameters? It prevents your code from SQL Injection and you don't have to convert values and code is much more readable. Look at sample (it is for select statement but the same works for insert/update/delete statement):
var connectionString = "some connection string";
using (var connection = new SqlConnection(connectionString)) {
connection.Open();
using (var command = new SqlCommand("SELECT * FROM Dogs1 WHERE Name LIKE #Name", connection)) {
command.Parameters.Add(new SqlParameter("Name", dogName));
var reader = command.ExecuteReader();
while (reader.Read()) {
int weight = reader.GetInt32(0);
string name = reader.GetString(1);
string breed = reader.GetString(2);
Console.WriteLine("Weight = {0}, Name = {1}, Breed = {2}",
weight,
name,
breed);
}
}
}
You are directly storing the text value of your controls in your numeric fields (contactno, pf_acc_no and basic_sal). Are the values really sql-string representations of numeric values?
I would try to convert them to numeric value
double dValue = 0.0;
double.TryParse(textBox1.Text, out dValue);
and then, in the sql string convert to their sql-string representations with dValue.ToString() or a special dedicated method.
As per your table structure, there are 3 fields that are of numeric datatype. These are - contactno, pf_acc_no and basic_sal
And the values for these fileds are txtcont.Text, txtqibacc.Text and txtnetsalary.Text respectively, And your are also putting ' around them, that is why they are being treated as varchar filed.
While constructing the sql statement, you should pass the values for these fields as numeric, which is to say without ' marks. So just remove ' before and after these fields and your query should work fine.
SqlCommand cmd = new SqlCommand("INSERT INTO Employee(
empcode,firstname,lastname,gender,address,contactno,bloodgroup,
dateofbirth, country,qid,passportno,passportexpiredate,designation,
doj,doexpid,pf_acc_no, agreementstartdate,agreementenddate,
department,basic_sal,remarks,empimage)
VALUES('" + txtempcode.Text + "','" + txtfrstname.Text + "',
'" + txtlstname.Text + "','" + combogender.Text + "','" +
txtaddr.Text + "'," + txtcont.Text + ",'" + txtblodgrp.Text + "', '" +
dob.Value.ToString("yyyy/MM/dd") + "' ,'" + txtcountry.Text + "','" + tqid.Text + "','" +
txtpassportno.Text + "', '" + passexpdate.Value.ToString("yyyy/MM/dd") + "' ,'" +
combodesig.Text + "', '" + doj.Value.ToString("yyyy/MM/dd") + "', '" + doexpqid.Value.ToString("yyyy/MM/dd") + "', " +
txtqibacc.Text + ", '" + agreestartdate.Value.ToString("yyyy/MM/dd") + "','" + agreeenddate.Value.ToString("yyyy/MM/dd") + "' ,'" + combobranch.Text + "'," + txtnetsalary.Text + ",'" + txtremark.Text + "',#empimage) ", cn);
In case you need to pass null to these numeric fields, use DBNull.Value as shown here -
Assign Null value to the Integer Column in the DataTable
Constructing queries like these are prone to SqlInjection, suggest to use parameterized queries instead.
Actually, your code is very vulnerable to SQL-injection attacks. But I don't changing your programming style; I'm changing just your insertion query:
SqlCommand cmd = new SqlCommand(#"
INSERT INTO Employee
(empcode, firstname, lastname, gender, address, contactno,
bloodgroup, dateofbirth, country, qid, passportno, passportexpiredate,
designation, doj, doexpid, pf_acc_no, agreementstartdate, agreementenddate,
department, basic_sal, remarks, empimage)
VALUES
('" + txtempcode.Text + "',
'" + txtfrstname.Text + "',
'" + txtlstname.Text + "',
'" + combogender.Text + "',
'" + txtaddr.Text + "',
" + txtcont.Text + ",
'" + txtblodgrp.Text + "',
'" + dob.Value.ToString("yyyy/MM/dd") + "' ,
'" + txtcountry.Text + "',
'" + tqid.Text + "',
" + txtpassportno.Text + ",
'" + passexpdate.Value.ToString("yyyy/MM/dd") + "' ,
'" + combodesig.Text + "',
'" + doj.Value.ToString("yyyy/MM/dd") + "',
'" + doexpqid.Value.ToString("yyyy/MM/dd") + "',
'" + txtqibacc.Text + "',
'" + agreestartdate.Value.ToString("yyyy/MM/dd") + "',
'" + agreeenddate.Value.ToString("yyyy/MM/dd") + "' ,
'" + combobranch.Text + "',
" + txtnetsalary.Text + ",
'" + txtremark.Text + "',
#empimage) ", cn);

Data type mismatch in criteria expression Oledb Access database

I'm getting the error:
Data type mismatch in criteria expression
When using this code. And using Access database.
OleDbConnection bab = new OleDbConnection();
bab.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\sdega\OneDrive\school\Werknemersdata.accdb;Persist Security Info=False;";
bab.Open();
try
{
OleDbCommand kaas = new OleDbCommand();
kaas.Connection = bab;
kaas.CommandText = "insert into Werknemersdata (Naam, Adres, Postcode, Woonplaats, Salaris) values ('" + txtNaam.Text + "', '" + txtAdress.Text + "', '" + txtpostcode1.Text + " " +txtpostcode2.Text + "', '" + txtwoonplaats.Text + "', '" + txtsalaris.Text + "') ";
kaas.ExecuteNonQuery(); // this is where it goes wrong
txtStatus.BackColor = Color.Green;
MessageBox.Show("data saved");
bab.Close();
}
catch (Exception ghakbal)
{
MessageBox.Show("Error" + ghakbal);
}
You missed one ' after '" + txtpostcode1.Text + " and one before " +txtpostcode2.Text + "' and also one , between them. It should be like this:
'" + txtpostcode1.Text + "' , '" +txtpostcode2.Text + "',
Also I strongly recommend that you always use parameterized queries to avoid SQL Injection. Like this:
kaas.CommandText = "insert into Werknemersdata (Naam, Adres, Postcode, Woonplaats, Salaris) values (?, ? ,.....");
kaas.Parameters.AddWithValue("Naam", txtNaam.Text);
kaas.Parameters.AddWithValue("Adres", txtAdress.Text);
//And other parameters...
Also It would be better to specify the type directly and use the Value property. Read more here.

Updating Database

So Visual Studio tells me that my quotes are not right in the update statement. I feel it might be something more than that. I feel I am close but I don't see where I am going wrong in this sql statement. The point of the webpage is to update the database that is all for this step. Can someone help me out.
Here is my code.
P.S. - I did an insert statement similar to this but the string idString part all the way to the softwareReportRecord.Close(); was beneath the update statement and it worked.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
reportDateText.Text = DateTime.Today.ToShortDateString();
//code page 429
if (Page.IsPostBack)
{
Page.Validate();
if (Page.IsValid)
{
bugReportForm.Visible = false;
regMessage.Visible = true;
string typeOS = oSListbox.SelectedValue;
string reportDate = reportDateText.Text;
string hardware = hardwareText.Text;
string occurrence = occurrenceRadioButtonList.SelectedValue;
string shortDescription = shortDescriptionText.Text;
string longDescription = longDescriptionText.Text;
string actionsTaken = actionsTakenText.Text;
SqlConnection dbConnection = new SqlConnection("Data Source=.\\SQLEXPRESS;Integrated Security=true");
try
{
dbConnection.Open();
dbConnection.ChangeDatabase("BugsReport");
}
catch (SqlException exception)
{
if (exception.Number == 911)
{
SqlCommand sqlCommand = new SqlCommand("CREATE DATABASE BugsReport", dbConnection);
sqlCommand.ExecuteNonQuery();
regMessage.Text = "<p>Successfully created the database.</p>";
dbConnection.ChangeDatabase("BugsReport");
}
else
Response.Write("<p>Error code " + exception.Number
+ ": " + exception.Message + "</p>");
}
finally
{
regMessage.Text += "<p>Successfully selected the database.</p>";
}
try
{
string SQLString = "SELECT * FROM softwareLog";
SqlCommand checkIDTable = new SqlCommand(SQLString, dbConnection);
SqlDataReader idRecords = checkIDTable.ExecuteReader();
idRecords.Close();
}
catch (SqlException exception)
{
if (exception.Number == 208)
{
SqlCommand sqlCommand = new SqlCommand("CREATE TABLE softwareLog (reportID SMALLINT IDENTITY(100,1) PRIMARY KEY, typeOS VARCHAR(25), reportDate DATE, hardware VARCHAR(50), occurrence VARCHAR(15), shortDescription VARCHAR(100), longDescription VARCHAR(500), actionsTaken VARCHAR(25))", dbConnection);
sqlCommand.ExecuteNonQuery();
regMessage.Text += "<p>Successfully created the table.</p>";
}
else
regMessage.Text += "<p>Error code " + exception.Number
+ ": " + exception.Message + "</p>";
}
finally
{
string idString = "SELECT IDENT_CURRENT('softwareLog') AS reportID";
SqlCommand newID = new SqlCommand(idString, dbConnection);
SqlDataReader softwareReportRecord = newID.ExecuteReader();
softwareReportRecord.Read();
string reportID = Convert.ToString(softwareReportRecord["reportID"]);
softwareReportRecord.Close();
string editRecord = "UPDATE softwareLog SET "
+ "typeOS='" + typeOS + "', "
+ "reportDate='" + reportDate + "', "
+ "hardware='" + hardware + "' "
+ "occurrence='" + occurrence + "' "
+ "shortDescription='" + shortDescription + "' "
+ "longDescription='" + longDescription + "' "
+ "actionsTaken='" + actionsTaken + "' "
+ "WHERE reportID=" + reportID + ";";
SqlCommand sqlCommand = new SqlCommand(editRecord, dbConnection);
sqlCommand.ExecuteNonQuery();
}
dbConnection.Close();
}
}
}
}
finally
{
string addRecord = "INSERT INTO softwareLog VALUES('"
+ typeOS + "', '"
+ reportDate + "', '"
+ hardware + "', '"
+ occurrence + "', '"
+ shortDescription + "', '"
+ longDescription + "', '"
+ actionsTaken + "')";
SqlCommand sqlCommand = new SqlCommand(addRecord, dbConnection);
sqlCommand.ExecuteNonQuery();
}
string idString = "SELECT IDENT_CURRENT('softwareLog') AS reportID";
SqlCommand newID = new SqlCommand(idString, dbConnection);
SqlDataReader softwareReportRecord = newID.ExecuteReader();
softwareReportRecord.Read();
string reportID = Convert.ToString(softwareReportRecord["reportID"]);
softwareReportRecord.Close();
regMessage.Text += "<p>Sorry for your inconvience. We will be working on your problem ASAP. For reference your ID is </p>" + reportID;
dbConnection.Close();
You are missing too many "," in Update.
EDIT You have single quote inside string. You need to escape those quotes also:
string editRecord = "UPDATE softwareLog SET "
+ "typeOS='" + typeOS.Replace("'", "''") + "', "
+ "reportDate='" + reportDate + "', "
+ "hardware='" + hardware.Replace("'", "''") + "',"
+ "occurrence='" + occurrence.Replace("'", "''") + "',"
+ "shortDescription='" + shortDescription.Replace("'", "''") + "',"
+ "longDescription='" + longDescription + "',"
+ "actionsTaken='" + actionsTaken.Replace("'", "''") + "'"
+ "WHERE reportID= " + reportID ;
In insert you don't need quote for reportID:
string addRecord = "INSERT INTO softwareLog VALUES('"
+ typeOS.Replace("'", "''") + "', '"
+ reportDate + "', '"
+ hardware.Replace("'", "''") + "', '"
+ occurrence.Replace("'", "''") + "', '"
+ shortDescription.Replace("'", "''") + "', '"
+ longDescription.Replace("'", "''") + "', '"
+ actionsTaken.Replace("'", "''") + "')";
Chances are the data being passed to the query be terminating the string early. For many reasons (including this one, but also SQL injection), you should be using parameters instead of concatenation.
Try like this,
string editRecord = "UPDATE softwareLog SET "
+ "typeOS='" + typeOS + "', "
+ "reportDate='" + reportDate + "', "
+ "hardware='" + hardware + "',"
+ "occurrence='" + occurrence + "',"
+ "shortDescription='" + shortDescription + "',"
+ "longDescription='" + longDescription + "',"
+ "actionsTaken='" + actionsTaken + "'"
+ "WHERE reportID=" + reportID + "";
Can you please Add your Insert Statement too.
Remarks : It will better to use Parametrized SqlCommand or Store
Procedure to perform this type of operation.
If you supply value with ' to any field then, it will not work. Also check value you supply for ReportId.
In this example you should be using parameters as a precaution against SQL injection as others have mentioned.
But for other strings I suggest you look into string.Format() rather than concatenating everything. Would make that string so much easier to read.

DateTime value from Oracle to MySql database

I have a question, how to parse datetime value from Oracle to MySQL database.
I wrote this to extract a datetime from Oracle:
SELECT TO_CHAR(p1.creation_date,'DD.MM.RRRR HH24:mi:ss') AS dat_pot
FROM TABLE
then I put the result into data set, then I extract the value of date from dataset like this:
string lDat_otp = null;
if (rw_mat["dat_otp"].ToString().Length <= 0)
{
lDat_otp = "0";
}
else
{
lDat_otp = "convert(datetime,'" + rw_mat["dat_otp"] + "',4)";
}
Then I use lDat_otp in INSERT statement with some other values like this:
myQuery = " INSERT INTO ordersstavke (BrDok, " +
" SifParFil, SifParIsp, DatPriOtpr, SifPodKla, Masa, Paketa) " +
" VALUES ('" + rw_mat["brdok"] + "', '" +
rw_mat["sifskl_kor"] + "','" +
rw_mat["partner"] + "'," +
lDat_otp + ",'" +
rw_det["ibrmat"] + "', '" +
rw_det["izlaz_tez"] + "', '" +
rw_det["izlaz_kol"] + "')";
But there is an error on execute and it goes:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '26.01.2012 13:48:41',4)','100654', '0', '10')' at line 1
So help!!!
You can parse the datetime field into a DateTime struct and then create an insert into query with parameters and pass the date as parameter :
DateTime time = //Some value ...
String myQuery = " INSERT INTO ordersstavke (BrDok, " +
" SifParFil, SifParIsp, DatPriOtpr, SifPodKla, Masa, Paketa) " +
" VALUES ('" + rw_mat["brdok"] + "', '" +
rw_mat["sifskl_kor"] + "','" +
rw_mat["partner"] + "'," +
"?date ,'" +
rw_det["ibrmat"] + "', '" +
rw_det["izlaz_tez"] + "', '" +
rw_det["izlaz_kol"] + "')";
MysqlCommand command = new MysqlCommand(query, connection);
command.Parameters.AddWithValue("?date", time);
Doing this you should not have problems with date formatting.
I strongly suggest to use parameters instead of string concatenation even for the others parameters of the query ...

Categories

Resources