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 ...
Related
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")
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);
I have a table which I had created using Toad. This has a field called created which is going to store the date of creation, so I need to insert the date of creation from the code behind using C# and an Oracle Connection.
But I am unable to insert the date. While doing so it's throwing the exception ORA-01843: not a valid month and when I try to use the to_date function it's showing that to_date couldn't be found in the current context in Microsoft Visual Studio.
I used the following code:
DateTime dt = DateTime.Today;
.
.
.
cmd.CommandText = "insert into Employee (BADGE_ID, USER_ID, FNAME, LNAME,PLANNED_ALLOC, MANAGER, TEAM,CREATED,CREATED_BY,LAST_UPD,LAST_UPD_BY) values ( '" + bid + "', '" + uid + "', '" + fn + "', '" + ln + "', " + pa + ", '" + man + "', '" + team + "', '" + TO_DATE(dt.ToString(), "yyyy/mm/dd hh24:mi:ss") + "', '" + uid + "', '" + TO_DATE(dt.ToString(), 'yyyy/mm/dd hh24:mi:ss') + "', '" + uid + "')";
So, in this case, I would say let the database do the work. Use the GETDATE() function in your SQL statement and the server will format a full timestamp and stick it in there.
The "TO_DATE" bit is part of the PL/SQL (you've got it as part of your c# command), so it should be part of the "CommandText" string.
So you want something like this:
cmd.CommandText = "insert into Employee (BADGE_ID, USER_ID, FNAME, LNAME,PLANNED_ALLOC, MANAGER, TEAM,CREATED,CREATED_BY,LAST_UPD,LAST_UPD_BY) values ( '" + bid + "', '" + uid + "', '" + fn + "', '" + ln + "', " + pa + ", '" + man + "', '" + team + "', '" + TO_DATE(dt.ToString(), "yyyy/mm/dd hh24:mi:ss") + "', '" + uid + "', TO_DATE(dt.ToString(), 'yyyy/mm/dd hh24:mi:ss') + ', '" + uid + "')";
[Notice I've removed the " (speech marks) which takes the TO_DATE out of the actual command string].
So it's got to be in the string that's "handed" to Oracle if you see what I mean.
Kind regards,
Mike
I'm trying to insert some data into my table and that's how I try to do it
INSERT INTO OrdersDetail
Values (" + OrderId.Text + ", (SELECT IdProduct FROM Products WHERE ProductName = '" + listBox1.Text + "'), '" + TypeOfProductComboBox.Text + "', '" + OrderQuantity.TextAlign + "', '" + TotalCost.Text + "'");
and I'm geting error I think my syntax is wrong, I'm use query in query to get the product id.
The columns are :
OrderId (int)
ProductId(int)
ProductName(Nvarchar)
OrderQuantity(Nvarchar)
TotalCost(NvarChar)
Thanks
You set your inside SELECT under '. Should be:
var query = "INSERT INTO OrdersDetail Values (" + OrderId.Text + ", (SELECT IdProduct FROM Products WHERE ProductName = '"+ listBox1.Text + "'), '" + TypeOfProductComboBox.Text + "', '" + OrderQuantity.TextAlign + "', '" + TotalCost.Text + "')");
If for example TotalCost.Text is a numeric data type in SQL, use
"..." + OrderQuantity.TextAlign + "', " + Convert.ToDouble(TotalCost.Text) + ")";
As p.s.w.g stated: This is open for SQL injection. Replace it with a parameterized version!
I think the problem is with the first Line and your inside Select.
This should work
INSERT INTO OrdersDetail
Values ('" + OrderId.Text + "',(SELECT IdProduct FROM Products WHERE ProductName ='"+ listBox1.Text + "')," + TypeOfProductComboBox.Text + "','" + OrderQuantity.TextAlign + "','" + TotalCost.Text + "'");
The problem is that you are missing the last bracket, the query should finish with "')" instead of "'" . The initial code started with opening bracket and that is why you didn't get compile errors.
But you should not create such sql queries, use Parameters to avoid SQL injection attacks. You code is vulnerable to them.
I have a windows service which inserts data into some tables. It does so fine when in debug mode, but when I install it says "Data type mismatch in criteria expression." for every insert.
query = "INSERT INTO printers (" +
"hostname," +
"ip_address," +
"model," +
"picture_id," +
"connect_type," +
"status," +
"product_number," +
"Floor_ID," +
"print_corner," +
"serial_number," +
"printer_features" +
") VALUES ('" +
exp.Devices[i].HostName.ToString() + "', '" +
exp.Devices[i].IpAddress.ToString() + "', '" +
exp.Devices[i].Model.ToString() + "', '" +
exp.Devices[i].PictureId.ToString() + "', '" +
exp.Devices[i].ConnectType.ToString() + "', '" +
exp.Devices[i].Status.ToString() + "', '" +
exp.Devices[i].ProductNumber.ToString() + "', '" +
exp.Devices[i].Floor.ToString() + "', '" +
exp.Devices[i].PrintCorner.ToString() + "', '" +
exp.Devices[i].SerialNumber.ToString() + "', '" +
exp.Devices[i].PrinterFeatures.ToString() +
"')";
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + confParams.MpaSearchDatabase;
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbCommand myCommand = new OleDbCommand(query);
myCommand.Connection = conn;
conn.Open();
myCommand.ExecuteNonQuery();
conn.Close();
insertedPrintersCount = insertedPrintersCount + 1;
Utils.Logger.Info("Device inserted: " + exp.Devices[i].HostName);
help!
The data type mismatch error indicates the query is expecting data of one type but you're providing another. This query expression is passing every value as a string literal but several columns indicate they are likely a numerical value. ProductNumber and SerialNumber for example.
In order to pass the values correctly (and prevent easy injection attacks) you'll want to use the OleDbCommand class to build up the call with values of the correct type. Then let the underlying infrastructure translate it to the appropriate values.