Isert new row in sql dosn't accept text - c#

I want to insert new row in my database from user input, i use C# and sql insert syntax. My problem is when i run a program all field compltely fill except text value (name of the product) which fill with another number (price) i check the syntax and the code but it's never work.
public DataBaseManager (string DataBaseFilename)
{
strFileName = DataBaseFilename;
strFileNamenopath = System.IO.Path.GetFileName(strFileName);
strAccessConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.IO.Path.GetFullPath(strFileName).Replace(System.IO.Path.GetFileName(strFileName), "") + "; Extended Properties=dBase III;Mode=ReadWrite";
conn = new OleDbConnection(strAccessConn);
conn.Open();
}
public void AddData(string Column, string value)
{
try
{
int i = 0;
char[] delimiterChars = { ','};
queryCutting = #"INSERT INTO [" + strFileNamenopath + "] ( " + Column + " ) VALUES ( " + value + " )";
OleDbCommand cmd = new OleDbCommand(queryCutting, conn);
string[] _valseperated = value.Split(delimiterChars);
string[] _columnsbase = Column.Split(delimiterChars);
foreach (string str in _columnsbase )
{
cmd.Parameters.AddWithValue(str,SqlDbType.VarChar).Value = _valseperated[i];
i++;
}
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
private void AddnewCode_Buttion_Click(object sender, RoutedEventArgs e)
{
_productBase.AddData("code, pv1, achat, designat", "123456789" + ", " + Textbox_Achat.Text + ", " + Textbox_Achat.Text +", " + Produitsnom_TextBox.Text);
}
Value of column represent the column name in databse , value is the text box value.
Column = "code, pv1, achat, designat";
Value = "123456789, 10, 10, Productname";
value of queryCutting
queryCutting = "INSERT INTO [produits.dbf] ( code, pv1, achat, designat ) VALUES ( 123456789, 540, 120, NewProduct)"

I think I have understood your problem. You set the Value string directly in the query text so you should get this result
"INSERT INTO [theFolderName] (code, pv1, achat, designat)
VALUES ( 123456789, 10, 10, Productname )";
The first three values are accepted as correct values for the numeric fields and no parameter is taken in consideration for these fields, but when the parser reaches the ProductName "value" it cannot use as a value because it is not a inside quotes. So it thinks it is a parameter and searches the Parameters collection. Because in OleDb parameters are positional, it takes the first parameter and passes its value to the OleDbCommand. And the first parameter is the Code.
This should solve the problem. Don't give a parameter name (OleDb doesn't care) and let the OleDbCommand use the complete set of parameters given in the exact order expected
public void AddData(string Column, string value)
{
try
{
char[] delimiterChars = { ','};
// Query text is incomplete, we complete it inside the loop
queryCutting = #"INSERT INTO [" + strFileNamenopath + #"]
( " + Column + " ) VALUES ( ";
// The query and the connection will be set after the loop
OleDbCommand cmd = new OleDbCommand();
string[] _valseperated = value.Split(delimiterChars);
string[] _columnsbase = Column.Split(delimiterChars);
foreach (string str in _columnsbase )
{
// The second parameter in AddWithValue is the Value not the type.
cmd.Parameters.AddWithValue(str, _valseperated[i]);
// Add a placeholder for each parameter
queryCutting += "?,";
}
// Remove the ending colon an close the paren on the query text
queryCutting = queryCutting.Substring(queryCutting.Length-1) + ")";
cmd.CommandText = queryCutting;
cmd.Connection = conn;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Notice that this code doesn't solve your Sql Injection problem. You should be absolutely sure that your user doesn't type itself neither the file name/folder neither the name of the columns and choose these values from a whitelisted set of values

I solved the problem by add insering Produitsnom_TextBox.Text betwwen qutes like this
_productBase.AddData("code, designat ,pv1, achat", "123456789" + ", " + "' " +Produitsnom_TextBox.Text + "'" + ", " + Vente_TextBox.Text + ", " + Textbox_Achat.Text );
also i removed the parametes part.
public void AddData(string Column, string value)
{
try
{
int i = -1;
char[] delimiterChars = { ',' };
queryCutting = #"INSERT INTO [" + strFileNamenopath + "] ( " + Column + " ) VALUES ( " + value + " )";
OleDbCommand cmd = new OleDbCommand(queryCutting, conn);
MessageBox.Show(queryCutting);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Related

C# Creating and Populating an Oracle Database

To start i don't have access to the database, we hit a problem with our university account and waiting for it to be reset. How ever i do have code that is giving me some problems and frankly i'm not sure i have even gone about this in the right way.
I am only trying to make a simple test program that creates a table, populates it then reads it.
If this isn't enough information i am sorry i should of waited but its bugging me getting these little errors in the code before i even get to a point i can compile to test tomorrow.
Here is the code to create the table, there does not seem to be any errors in the code
static void buildTable()
{
try
{
string sqlBuild = "CREATE TABLE Item ("
+ "Item_ID VARCHAR2(1),"
+ "Item_Name VARCHAR2(16),"
+ "Price_Consumer VARCHAR(5)"
+ " ); ";
OracleCommand cmd = new OracleCommand(sqlBuild, con);
Connect();
cmd.ExecuteNonQuery();
Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Here is the code to populate the table and this is where i am getting errors.
static void populateTable()
{
string[,] items;
items = new string[5,3] { { "1", "Mozzarella", "9.99" }, { "2", "Peperoni", "12.99" }, { "3", "Meat Feast", "14.99" }, { "4", "Chicken Tikka", "12.99" }, { "5", "Spicy Vegetarian", "11.99" } };
try
{
OracleCommand cmd = new OracleCommand();
OracleDataReader r = cmd.ExecuteReader();
r.Read();
for (int i = 1; i < 6; i++)
{
for(int j = 1; j < 4; j++)
{
OracleCommand comd = new OracleCommand();
comd.Connection = con;
comd.CommandText = "insert into Item(Item_ID, Item_Name, Price_Consumer) values(" items[i, j].ToString() + ", " + items[i, j].ToString() + ", " + items[i, j].ToString() ");";
Connect();
comd.ExecuteNonQuery();
Close();
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
the errors are on the items[i,j], it tells me it expects an " ; "
lastly this is what im near 100% will work as this i have done in the past, but i have never tried to use c# to create or populate a table.
static void itemList()
{
string s = "\n";
try
{
Connect();
OracleCommand cmd = new OracleCommand(sql, con);
OracleDataReader r = cmd.ExecuteReader();
r.Read();
while (r.Read())
{
s = s + r["Item_ID"].ToString() + ", " + r["Item_Name"].ToString() + ", " + "£" +r["Price_Consumer"].ToString();
}
Close();
Console.WriteLine(s);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
here is the addtional code that might be relevant
static void Connect()
{
con = new OracleConnection();
con.ConnectionString = "User Id=username;Password=password;Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=host)(PORT=port))(CONNECT_DATA=(SERVICE_NAME=SID)))";
con.Open();
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
}
static void Close()
{
con.Close();
con.Dispose();
}
Declarations
static OracleConnection con;
static string sql = "select * from Item";
Your internal loop is not needed. When you try to insert a row, you don't call the insert one time for each column, but you call the insert one time for each row
Another problem are your columns of type VARCHAR, this means that you need to insert strings there, but you don't do it correctly.
This could be solved putting single quotes around those string to be recognized as such by the database engine.
for (int i = 1; i < 6; i++)
{
comd.CommandText = #"insert into Item(Item_ID, Item_Name, Price_Consumer)
values('" + items[i, 0].ToString() + "', '" +
items[i, 1].ToString() + "', '" +
items[i, 2].ToString() '");";
However while this will work for your simple example, this is still wrong. You should never concatenate string to build an sql command. This leads to Sql Injection and to a parsing error if the value to insert contains a single quote.
The only correct way to do it is through a parameterized query as this
comd.CommandText = #"insert into Item(Item_ID, Item_Name, Price_Consumer)
values(:ID, :Name, :Price)";
comd.Parameters.AddWithValue(":ID", items[i, 0].ToString());
comd.Parameters.AddWithValue(":Name",items[i, 1].ToString());
comd.Parameters.AddWithValue(":Price",items[i, 2].ToString());
(As a side benefit, look at how the command is more understandable now)
This line is not well formatted and is missing two + symbols:
comd.CommandText = "insert into Item(Item_ID, Item_Name, Price_Consumer) values(" +
items[i, j].ToString() + ", " +
items[i, j].ToString() + ", " +
items[i, j].ToString() + ");";
If you split it in a similar way to the above then it is easier to spot the errors
You are missing a '+' sign here

Error in C# insert statement for SQL Server

I am trying to pass an insert statement in a C# Winforms to SQL Server. I keep getting a syntax error that just doesn't make sense to me
error in syntax near "("
My syntax is perfectly fine, as when I copy and paste into SQL Server Mgmt Studio, the code runs perfectly.
Any help would be greatly appreciated!
Thanks!
try
{
using (var cmd = new SqlCommand("INSERT INTO " + intodrop.SelectedText + "(" + colnamedrop.SelectedText.ToString() + "," +
colnamedrop2.SelectedText.ToString() + ") " + "VALUES" + " (" + valuebox.Text + ");"))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#tbl", intodrop.SelectedText);
cmd.Parameters.AddWithValue("#colname", colnamedrop.SelectedText);
cmd.Parameters.AddWithValue("#values", valuebox.Text);
cmd.Parameters.AddWithValue("#colname2", colnamedrop2.SelectedText);
con.Open();
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
}
catch (Exception g)
{
MessageBox.Show("Error during insert: " + g.Message);
}
Check if SelectedText property returns right values. Try to use Text property instead.
var cmd = new SqlCommand("INSERT INTO " + intodrop.Text +
"(" + colnamedrop.Text + ',' + colnamedrop2.Text + ") "
+ "VALUES" + " (" + valuebox.Text + ");")
You missed comma between column names when insert sql statement preparing. When printing you have comma and display correctly.
Concatenated sql statement without any inputs validation is widely open for sql injection attacks. Try to use parameter as much as possible.
It looks like you are trying to insert values to two columns, but you are appending them like this "Col1+Col2", instead of "Col1+','+Col2".
using (var cmd = new SqlCommand("INSERT INTO " + intodrop.SelectedText + "(" + colnamedrop.SelectedText.ToString() + ','+
colnamedrop2.SelectedText.ToString() + ") " + "VALUES" + " (" + valuebox.Text + ");"))
I hope this resolves the issue.
First try hard coding your insert value after that change it based on your need. Confirm the column data types are assigned correctly.
try
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Property ( FolioNo,PropertyType) VALUES (001,'WIP')"))
{
cmd.Connection = con;
con.Open();
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
}
catch (Exception g)
{
MessageBox.Show("Error during insert: " + g.Message);
}
1) You should have two texbox for entering your values. If no column names you gray the value of column 1, ditto for column 2.
This allows you not to have to enter quote (do not forget to make an escape quotes
2) use the string.format function for more readability
try
{
//Add columns selected
List<string> Mycolumns = new List<string>();
If (! string.IsNullOrEmpty(colnamedrop.Text)) Mycolumns.Add(colnamedrop.Text);
If (! string.IsNullOrEmpty(colnamedrop2.Text)) Mycolumns.Add(colnamedrop2.Text);
//Add values selected with escaped quoted and string quoted
List<string> Myvalues ​​= new List<string>();
If (! string.IsNullOrEmpty(colvalue1.Text)) Myvalues.Add("'" + colvalue1.Text.Replace("'", "''") + "'");
If (! string.IsNullOrEmpty(colvalue2.Text)) Myvalues.Add("'" + colvalue2.Text.Replace("'", "''") + "'");
//If nothing selected, no action
if (Mycolumns.Count==0 && Myvalues.Count==0) return;
//Build query
String Query = string.Format ( "INSERT INTO {0} ({1}) VALUES ({2})", intodrop.Text, string.Join(Mycolumns, ", "), string.Join(Myvalues, ", "));
//Execute query
using (var cmd = new SqlCommand(Query, con ))
{
con.Open();
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
con.Close();
}
}
catch (Exception g)
{
MessageBox.Show("Error during insert: " + g.Message);
}

Method returns empty string in ASP.Net

I'm having trouble with this method. It returns empty string, what is wrong with this ?
I have this method:
public static string GetData(string Table1, string Column1, string WhereColumn, string WhereValue)
{
Table1 = Methods.cleaninjection(Table1); // Some injection method that cleans the string
SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["connection"].ConnectionString);
SqlCommand command = new SqlCommand("SELECT " + "#Column1" + " FROM " + Table1 + " WHERE " + "#WhereColumn" + " = " + "#WhereValue", connection);
command.Parameters.AddWithValue("Column1", Column1);
command.Parameters.AddWithValue("WhereColumn", WhereColumn);
command.Parameters.AddWithValue("WhereValue", WhereValue);
try
{
if ((connection.State == ConnectionState.Closed) || (connection.State == ConnectionState.Broken))
{
connection.Open();
}
string veri = Convert.ToString(command.ExecuteScalar());
return veri;
}
finally
{
connection.Close();
}
}
When I run this, the command string looks like this:
SELECT #Column1 FROM Table1 WHERE #WhereColumn = #WhereValue
It looks like correct but I couldn't find what is wrong.
Any ideas?
As commented, you cannot parameterize your column names and table names. Instead, do string concatenation:
"SELECT " + Column1 + " FROM " + Table1 + " WHERE " + WhereColumn + " = #WhereValue";
Here is how your code should be:
public static string GetData(string Table1, string Column1, string WhereColumn, string WhereValue)
{
Table1 = Methods.cleaninjection(Table1); // My injection method that cleans the string
string sql = "SELECT " + Column1 + " FROM " + Table1 + " WHERE " + #WhereColumn + " = #WhereValue";
using (SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["connection"].ConnectionString))
{
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#WhereValue", SqlDbType.VarChar, 50).Value = WhereValue;
connection.Open();
string veri = Convert.ToString(command.ExecuteScalar());
return veri;
}
}
}
Notes:
Please do not use AddWithValue. Use Parameters.Add() instead. According to this article:
There is a problem with the AddWithValue() function: it has to infer
the database type for your query parameter. Here’s the thing:
sometimes it gets it wrong.
Wrap your object in Using to ensure proper cleanup of resources.
For additional security purposes, you can wrap your column name and table name in square brackets [].

get different column value from two tables which has same primary key in c#

I have two tables with same name/schema but with different values.
I need to find the row which has same primary key(1st column) but different values.
ex.
my-table:
id name age
1 ram 25
2 mohan 30
my-table:
id name age
3 harry 26
**1 ram 35**
3 tony 45
So I need 2 row from 2 table with value 35.
It should return whole row as data table or data row.
I am using oracle database. needed c# code for this solution.
and it should work for multiple column values for other tables also.
my code..
public OracleCommand getColumns(OracleConnection connection, DataTable table, int i, string tab, DataTable table3)
{
int columCount = table.Columns.Count;
string [] colArray = new string[columCount];
string pkey = table.Columns[0].ColumnName;
string pkeyValue = table.Rows[i][0].ToString();
string query2 = "SELECT * FROM " + tab +
" WHERE " + tab + "." + pkey + " = '" + pkeyValue + "'";
OracleCommand command = new OracleCommand();
int k = 0;
int X =0;
for(int j=1 ; j<colArray.Length;j++)
{
string column = table.Columns[j].ColumnName;
string columnValue = table.Rows[i][j].ToString();
string add = " OR " + tab + "." + column + " = '" + columnValue + "'";
query2 += add;
command.CommandText = query2;
command.CommandType = CommandType.Text;
command.Connection = connection;
var check = command.ExecuteNonQuery();
if (check == null)
{
k++;
}
else
X++;
}
return command;
}
Here is example for your tables, I am presenting data from t2 which do not match rows in t1:
using Oracle.DataAccess.Client;
...
public string OraText(string pkey, string[] tables, string[] columns)
{
string sSQL = "select " + pkey + "";
foreach (string s in columns)
{
sSQL += ", " + tables[1] + "." + s;
}
sSQL += Environment.NewLine + " from t1 join t2 using (" + pkey + ") "
+ Environment.NewLine + " where 1=0 ";
foreach (string s in columns)
{
sSQL += " or " + tables[0] + "." + s + " <> " + tables[1] + "." + s;
}
return sSQL;
}
private void Form1_Load(object sender, EventArgs e)
{
OracleConnection oc = new OracleConnection(
"User Id=scott;Password=tiger;Data Source=XE");
oc.Open();
string[] tables = {"t1", "t2"};
string[] columns = {"name", "age"};
string sSQL = OraText("id", tables, columns);
OracleCommand oracmd = new OracleCommand(sSQL, oc);
OracleDataReader reader = oracmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetValue(0) + " "
+ reader.GetValue(1) + " " +reader.GetValue(2));
}
oc.Close();
}
Console output:
1 ram 35

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

Categories