How to insert an number value to a oracle db - c#

i have a problem with my code. My code is working fine, but i want to insert a decimal number in my oracle table (the type of the field in oracle is number).
"Gewicht" is a textfield where the user have to type a decimal number in. actually i can insert just full numbers but i cant insert decimal.
my oracle datafields:
TOUR - VARCHAR2 (20 BYTE)
GEWICHT - NUMBER
I have no much experience about programming so i give my best. Its my first Script :).
private void insert()
{
try
{
String connectionString = "Data Source = (DESCRIPTION = " +
"(ADDRESS = (PROTOCOL = TCP)(HOST = IP-Adress)(PORT = 1521))" +
"(CONNECT_DATA =" +
" (SERVER = DEDICATED)" +
" (SERVICE_NAME = NAME)" +
")" +
");User Id = USER;password=password;";
OracleConnection con = new OracleConnection();
con.ConnectionString = connectionString;
con.Open();
OracleCommand cmd = new OracleCommand();
cmd.CommandText = "insert into TABLENAME (TOUR,GEWICHT) values ('" + this.comboBox1.Text + "'," + Gewicht.Text+ ")";
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Erfolgreich eingefügt");
comboBox1.Text = String.Empty;
Gewicht.Clear();
viewdata();
}
catch (Exception ex)
{
MessageBox.Show("Fehler");
}

You are missing quotes in your insert query string. In any case, use parameters like:
cmd.CommandText = "insert into TABLENAME (TOUR,GEWICHT) values (#tour,#wicht)";
cmd.Parameters.Add("#tour", OracleDbType.NVarChar2).Value = this.comboBox1.Text;
cmd.Parameters.Add("#wicht", OracleDbType.Decimal).Value = Decimal.Parse(Gewicht.Text);

Related

String meant to store date in a table is converting an int for unknown reason

I'm trying to get the date to store as a string in a table, but the date keeps converting to a negative 4 digit number which correlates with the date, and I can't for the life of me figure out where I've messed up. Note that I'm using a combo of C# and SQL Server
foreach(DataRow dr in dt.Rows)
{
int qty = 0;
string pname = "";
SqlCommand cmd3 = con.CreateCommand();
cmd3.CommandType = CommandType.Text;
cmd3.CommandText = "insert into order_item values('" + orderid.ToString() + "','" + dr["product"].ToString() + "'," +
"'" + dr["price"].ToString() + "','" + dr["qty"].ToString() + "','"+ dr["total"].ToString() + "')";
cmd3.ExecuteNonQuery();
qty = Convert.ToInt32(dr["qty"].ToString());
pname = dr["product"].ToString();
SqlCommand cmd6 = con.CreateCommand();
cmd6.CommandType = CommandType.Text;
cmd6.CommandText = "update stock set product_qty = product_qty - " + qty + " where product_name = '"+pname.ToString()+"'";
cmd6.ExecuteNonQuery();
// date keeps getting updated to negative 4 digit number which coordinates with the date. ex: 14-01-2020 is converting to -2007.
SqlCommand cmd7 = con.CreateCommand();
cmd7.CommandType = CommandType.Text;
**cmd7.CommandText = "update stock_over_time set product_qty = product_qty - " + qty + ", date_changed = " + date.ToString("dd-MM-yyyy") + "" +
" where product_name = '" + pname.ToString() + "'";**
cmd7.ExecuteNonQuery();
}
The immediate problem is that:
, date_changed = " + date.ToString("dd-MM-yyyy") + "
will become
, date_changed = 15-01-2020
which is: -2006, which is (because of how dates are stored) some time in July 1894.
A bad fix for this would be to add quotes, but this is: bad - it has a range of problems to do with internationalization (is 08-01 the first of August? the 8th of January?), SQL injection, etc.
The correct fix is to use parameters throughout. For example:
cmd7.CommandText = #"
update stock_over_time
set product_qty = product_qty - #qty,
date_changed = #date
where product_name = #pname";
This, however, requires you to add parameters with the values.
The simplest way to do this would be with Dapper:
string pname = ...
int qty = ...
DateTime date = ...
con.Execute(#"
update stock_over_time
set product_qty = product_qty - #qty,
date_changed = #date
where product_name = #pname",
new { pname, qty, date });
Note: all of your database access should be parameterized, either like the above, or using raw ADO.NET, or using tools like EF etc. Not just this one place; everywhere.
A date should not be stored as a string datatype, instead change date-changed to a datetime type (or even just a date, since the values stored have no "time" element).
Also, it is advisable to use a parameterized query to avoid SQL injection
string sql = #"update stock_over_time set product_qty = product_qty - #qty, date_changed = #date where product_name = #pname";
using (SqlConnection connection = new SqlConnection(connString)
{
connection.Open();
using (SqlCommand cmd= new SqlCommand(sql, connection))
{
cmd.Parameters.Add("#qty", SqlDbType.SqlInt32).value = qty;
cmd.Parameters.Add("#date", SqlDbType.SqlDateTime).value = date;
cmd.Parameters.Add("#pname", SqlDbType.Varchar, 50).value = pname;
cmd.ExecuteNonQuery();
}
}

run SQL Commands from text box value

i create small project that read data from sqlserver then insert into mysql table.
i want to users write SQL and mysql command into textbox.
here is my problem, when i run project the field that inserted into mysql table are: myReader["STableName"].ToString()
like this picture:
connections are fine, here is my code:
string address;
string username;
string password;
string database;
address = textBox1.Text;
username = textBox2.Text;
password = textBox3.Text;
database = textBox4.Text;
//MySql
string mysqladdress;
string mysqlusername;
string mysqlpassword;
string mysqldatabase;
mysqladdress = textBox7.Text;
mysqlusername = textBox8.Text;
mysqlpassword = textBox9.Text;
mysqldatabase = textBox10.Text;
//SQLCode
string sqlcmnd1;
string sqlcmnd2;
sqlcmnd1 = textBox5.Text;
sqlcmnd2 = textBox6.Text;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=" + address + ";" +
"Initial Catalog=" + database + ";" +
"User id=" + username + ";" +
"Password=" + password + ";";
try
{
conn.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand(sqlcmnd1, conn);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
string connectionString = #"server=" + mysqladdress + ";" + "username=" + mysqlusername + ";" + "password=" + mysqlpassword + ";" + "database=" + mysqldatabase + "";
MySqlConnection connection = null;
MySqlDataReader reader = null;
try
{
connection = new MySqlConnection(connectionString);
connection.Open();
string stm = sqlcmnd2;//here is my problem
MySqlDataAdapter dataAdapter = new MySqlDataAdapter();
dataAdapter.SelectCommand = new MySqlCommand(stm, connection);
DataTable table = new DataTable();
dataAdapter.Fill(table);
}
sqlcmnd2:
INSERT INTO test (CusCode,STableName,Date,ModdatZaman) VALUES ('" + myReader["CusCode"].ToString() + "','" + myReader["STableName"].ToString() + "','" + myReader["Date"].ToString() + "','" + myReader["ModdatZaman"].ToString() + "')
sqlcmnd1:
SELECT * FROM __TempUserCompRep__
Text from a textbox is considered as a full string it not replace the actual value of the variable .
You need to use prepared statement for that.
In textbox6 you write the command like this :
INSERT INTO test (CusCode,STableName,Date,ModdatZaman) VALUES (#CusCode,#STableName,#Date,#ModdatZaman)
After that in code, bind the parameter with variable from you actually want to take value.
For example:
MySqlConnection con = null;
try
{
string myConnectionString = "server=localhost;database=test;uid=root;pwd=root;";
con = new MySqlConnection(myConnectionString);
string CmdString = textBox6.Text.ToString();
MySqlCommand cmd = new MySqlCommand(CmdString, con);
cmd.Parameters.Add("#CusCode", MySqlDbType.VarChar, 50);
cmd.Parameters.Add("#STableName", MySqlDbType.VarChar, 50);
cmd.Parameters.Add("#Date", MySqlDbType.VarChar, 50);
cmd.Parameters.Add("#ModdatZaman", MySqlDbType.VarChar, 50);
cmd.Parameters["#CusCode"].Value = myReader["CusCode"].ToString();
cmd.Parameters["#STableName"].Value = myReader["STableName"].ToString();
cmd.Parameters["#Date"].Value = myReader["Date"].ToString();
cmd.Parameters["#ModdatZaman"].Value = myReader["ModdatZaman"].ToString();
con.Open();
int RowsAffected = cmd.ExecuteNonQuery();
if (RowsAffected > 0)
{
MessageBox.Show("Insert Query sucessfully!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con != null && con.State == ConnectionState.Open)
{
con.Close();
}
}
Note: I consider all four columns are varchar type in the database. you modify it according to your requirement
Hello Muhammad i would suggest you not to execute the sql commands from text box as there is a high chance of sql injection attacks , try to avoid as much you can , its a suggestion for more secured application

how to insert date(long format) into access database using datetimepicker in c# ? (error is in date part only)

Error image is here
the error is in query line , its shows syntax error
try
{
string zero = "0";
DateTime dat = this.dateTimePicker1.Value.Date;
connection1.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection1;
command.CommandText = "insert into client_table(CLIENT, DATE,BILL_AMOUNT, PAID_AMOUNT, BALANCE, CONTACT, ADDRESS )VALUES ('" + txt_client.Text + "', #" + dat.ToLongDateString() + "# ,'" + zero + "','" + zero + "','" + zero + "','" + txt_contact.Text + "','" + txt_address.Text + "')";
command.ExecuteNonQuery();
connection1.Close();
MessageBox.Show("New Client Registration done Successfully.");
connection1.Dispose();
this.Hide();
employee_form f1 = new employee_form("");
f1.ShowDialog();
}
thank you in advance
In Access, dates are delimited by #, not '. Also, Access does not recognize the long date format. But dates are not stored in any format so no worries, change it to:
... + "', #" + dat.ToString() + "# ...etc.
Although if you do not parameterize your query serious damage or data exposure can be done through SQL Injection because someone could type in a SQL statement into one of those textboxes that you are implicitly trusting.
Working example:
class Program
{
static void Main(string[] args)
{
System.Data.OleDb.OleDbConnectionStringBuilder bldr = new System.Data.OleDb.OleDbConnectionStringBuilder();
bldr.DataSource = #"C:\Users\tekhe\Documents\Database2.mdb";
bldr.Provider = "Microsoft.Jet.OLEDB.4.0";
using (System.Data.OleDb.OleDbConnection cnxn = new System.Data.OleDb.OleDbConnection(bldr.ConnectionString))
{
cnxn.Open();
Console.WriteLine("open");
using (System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand())
{
cmd.Connection = cnxn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO [Table1] ([Dob]) VALUES(#" + DateTime.Now.ToString() + "#)";
cmd.ExecuteNonQuery();
}
}
Console.ReadKey();
}
}
Update
However, you want to do something more like this which uses Parameters to protect against SQL Injection which is extremely easy to exploit so do not think that you don't really need to worry about it:
static void Main(string[] args)
{
OleDbConnectionStringBuilder bldr = new OleDbConnectionStringBuilder();
bldr.DataSource = #"C:\Users\tekhe\Documents\Database2.mdb";
bldr.Provider = "Microsoft.Jet.OLEDB.4.0";
using (System.Data.OleDb.OleDbConnection cnxn = new OleDbConnection(bldr.ConnectionString))
{
cnxn.Open();
Console.WriteLine("open");
using (System.Data.OleDb.OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = cnxn;
cmd.CommandType = System.Data.CommandType.Text;
OleDbParameter dobParam = new OleDbParameter("#dob", OleDbType.Date);
dobParam.Value = DateTime.Now;
cmd.Parameters.Add(dobParam);
cmd.CommandText = "INSERT INTO [Table1] ([Dob]) VALUES(#dob)";
cmd.ExecuteNonQuery();
}
}
Console.ReadKey();
}
//code to write date in the access table.
string zero = "0";
DateTime dat = this.dateTimePicker1.Value.Date;
//MessageBox.Show(dat.ToShortDateString());
connection1.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection1;
//command.CommandText = "insert into client_table(DATEE) values( '"dat.ToShortDateString()+"')";
command.CommandText = "insert into client_table (CLIENT, DATEE, BILL_AMOUNT, PAID_AMOUNT, BALANCE, CONTACT, ADDRESS )VALUES ('" + txt_client.Text + "', #"+dat.ToShortDateString()+"# ,'" + zero + "','" + zero + "','" + zero + "','" + txt_contact.Text + "','" + txt_address.Text + "')";
command.ExecuteNonQuery();
connection1.Close();
MessageBox.Show("New Client Registration done Successfully.");
connection1.Dispose();
//New code for receiving the date between two range of dates
try
{
DateTime dat = this.dateTimePicker1.Value.Date;
DateTime dat2 = this.dateTimePicker2.Value.Date;
// MessageBox.Show(dat.ToShortDateString() + " " + dat2.ToShortDateString());
connection1.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection1;
string query;
query = "select * from client_table Where DATEE Between #" + dat.ToLongDateString() +"# and #" + dat2.ToLongDateString() + "# ";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection1.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
Thank you all of you for the support.

my update c# code is not working,can i update two relational table at once?

i was trying to update two tables at once, but i got some syntax error on update code could u give me some idea? the insert code works perfect and i tried to copy the insert code and edit on update button clicked
here is my code
private void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Users\user\Documents\Visual Studio 2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\crt_db.accdb";
try
{
conn.Open();
String Name = txtName.Text.ToString();
String AR = txtAr.Text.ToString();
String Wereda = txtWereda.Text.ToString();
String Kebele = txtKebele.Text.ToString();
String House_No = txtHouse.Text.ToString();
String P_O_BOX = txtPobox.Text.ToString();
String Tel = txtTel.Text.ToString();
String Fax = txtFax.Text.ToString();
String Email = txtEmail.Text.ToString();
String Item = txtItem.Text.ToString();
String Dep = txtDep.Text.ToString();
String k = "not renwed";
String Remark = txtRemark.Text.ToString();
String Type = txtType.Text.ToString();
String Brand = txtBrand.Text.ToString();
String License_No = txtlicense.Text.ToString();
String Date_issued = txtDate.Text.ToString();
String my_querry = "update crtPro set Name='" + Name + "',AR='" + AR + "',Wereda='" + Wereda + "',Kebele='" + Kebele + "',House_No='" + House_No + "',P_O_BOX='" + P_O_BOX + "',Tel='" + Tel + "',Fax='" + Fax + "',Email='" + Email + "',Item='" + Item + "',Dep='" + Dep + "','" + k + "',Remark='" + Remark + "' where Name='" + Name + "' ";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.ExecuteNonQuery();
String my_querry1 = "SELECT max(PID) FROM crtPro";
OleDbCommand cmd1 = new OleDbCommand(my_querry1, conn);
string var = cmd1.ExecuteScalar().ToString();
String ki = txtStatus.Text.ToString();
String my_querry2 = "update crtItemLicense set PID=" + var + ",Type='" + Type + "',Brand='" + Brand + "',License_No='" + License_No + "',Date_issued='" + Date_issued + "' where PID=" + var + "";
OleDbCommand cmd2 = new OleDbCommand(my_querry2, conn);
cmd2.ExecuteNonQuery();
MessageBox.Show("Message added succesfully");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
conn.Close();
}
The most likely problem based on the little information given (what database are you using for example - SQL Server 2012?), is that the datatype you are providing in the concatenated dynamic sql does not match the datatype of the column in the database. You've surrounded each value with quotes - which means it will be interpreted as a varchar. If you've got a date value in the wrong format (ie if Date_Issued is a date column) or if it is a number column, then it will error.
The solution is to replace your dynamic SQL with a parameterized query eg:
String my_querry = "update crtPro set Name=#name, AR=#ar, Wereda=#Wereda, etc ...";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#name", Name);
cmd.Parameters.AddWithValue("#myParam", Convert.ToDateTime(txtDate.Text.Trim()));
...
cmd.ExecuteNonQuery();
You can read about it further here
PS Make sure your parameters are in the same order as they are used in the SQL, because oledbcommand doesn't actually care what you call them. see here

ASP.NET is not sending a command to a SQL server

I have been assigned to create a website for a club at my school at kmhsmc.somee.com. I choose ASP for the language and I am having an issue with a sql function. If you go to the website above and click on join current liveclub session and fill in a bunch of junk in the textboxes at the top and hit join, it throws a SQL exception. here is the code:
UName = TextBox1.Text;
CompN = TextBox2.Text;
TMin = TextBox3.Text;
Name = TextBox4.Text;
TextBox1.Visible = false;
TextBox2.Visible = false;
TextBox3.Visible = false;
TextBox4.Visible = false;
string sql = "INSERT INTO table_name values (" + Name + "," + UName + "," + CompN + "," + TMin + "," + "NA" + "," + 0 + ")";
conn.Open();
try
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch
{
Response.Write("<script>alert('SQL error: try again later')</script>");
}
finally
{
conn.Close();
}
And for anyone who asks, I am 110% sure it is not the connection string because it works just fine on the calender page of the site.
Here is some other relevant information about this project:
I am doing it in C# and HTML ONLY (CSS and other designing things will be done by someone else later)
The server uses SQL server 2012
Problem : you are not enclosing the String types VARCHAR,NVARCHAR columns inside single quotes.
Solution : you need to enclose the String types inside single quotes.
Try This:
sqlCmd.CommandText = "INSERT INTO tablename(name) VALUES('yourname');
Suggestion : You should use Parameterised queries to avoid SQL injection attacks.
Complete Code: using parameterised sql queries
string sql = "INSERT INTO table_name values (#Name,#UName,#CompN,#TMin,#value1,#value2)";
conn.Open();
try
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#Name",Name);
cmd.Parameters.AddWithValue("#UName",UName);
cmd.Parameters.AddWithValue("#CompN",CompN);
cmd.Parameters.AddWithValue("#TMin",TMin);
cmd.Parameters.AddWithValue("#value1","NA");
cmd.Parameters.AddWithValue("#value2",0);
cmd.ExecuteNonQuery();
}
your sql string is wrong.
UName = TextBox1.Text;
CompN = TextBox2.Text;
TMin = TextBox3.Text;
Name = TextBox4.Text;
TextBox1.Visible = false;
TextBox2.Visible = false;
TextBox3.Visible = false;
TextBox4.Visible = false;
string sql = "INSERT INTO table_name values ('" + Name + "','" + UName + "','" + CompN + "','" + TMin + "','NA', 0 )";
conn.Open();
try
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch
{
Response.Write( "<script>alert( 'SQL error: try again later' )</script>" );
}
finally
{
conn.Close();
}

Categories