简体   繁体   中英

Insert command with comma

I am inserting a row in Oracle. But the problem is that I want to insert comma in the companyname column, which fails due to insert statement.

Wonder is it possible to add comma or apostrophy using following insert command?

string id=1;
string orgnr = "123123";
comanyname = "Test,company";

string sql = 
  string.Format("INSERT INTO VENDORS(ID, ORGNR, COMPANYNAME) " +
  "VALUES({0}, '{1}', '{2}')", id, orgnr, companyname);

update = new OracleCommand(sql, connection);
update.Connection.Open();
update.ExecuteNonQuery();
update.Connection.Close();

It is failing because you have declared 'id' as string and you have been trying to insert it without single quote. Also there are illegal characters to escape in the string parameters. Would you like to get rid of these? Please continue to read...

There is a bigger issue in your code where you haven't used parameterized queries. This piece of code turning host application into a SQL Injection playground.

Please have a look at the following code:

int id=1;
string orgnr = "123123";
string companyName = "Test,company";

string connectionString = "Data Source= oraDB;User Id=;Password=;";
OracleConnection connection = new OracleConnection(connectionString);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = connection;

cmd.CommandText = "INSERT INTO VENDORS(ID, ORGNR, COMPANYNAME) VALUES (:1, :2, :3)";

cmd.Parameters.Add(new OracleParameter("1",
                                       OracleDbType.Int32,
                                       id,
                                       ParameterDirection.Input));

cmd.Parameters.Add(new OracleParameter("2",
                                       OracleDbType.Varchar2,
                                       orgnr,
                                       ParameterDirection.Input));

cmd.Parameters.Add(new OracleParameter("3",
                                       OracleDbType.Varchar2,
                                       companyName,
                                       ParameterDirection.Input));

int rowsUpdated = cmd.ExecuteNonQuery();
connection.Dispose();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM