Oracle PreparedStatement / Parameter error - c#

Using this code I am able to get data from Oracle database.
public static ArrayList CheckIfPrinterExists()
{
string printerName = #"PRINTER1234";
ArrayList colValues = new ArrayList();
try
{
string constr = #"DATA SOURCE=someSource;PERSIST SECURITY INFO=True;USER ID=root;password=root";
OracleConnection con = new OracleConnection(constr);
con.Open();
OracleCommand cmd = con.CreateCommand();
cmd.CommandText = #"select * from print_spooler where spoolername = 'Printer1234'";
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
colValues.Add(reader["id"] + ";" + reader["id2"] + ";" + reader["id3"]);
}
con.Dispose();
reader.Dispose();
return colValues;
}
catch (Exception ex)
{
Console.WriteLine("Error : {0}", ex);
return null;
}
}
I tried modifiying the code using prepared statement which is not working. What am I doing wrong here?
public static ArrayList CheckIfPrinterExists()
{
string printerName = #"printer1234";
ArrayList colValues = new ArrayList();
try
{
string constr = #"DATA SOURCE=someSource;PERSIST SECURITY INFO=True;USER ID=root;password=root";
OracleConnection con = new OracleConnection(constr);
con.Open();
OracleCommand cmd = con.CreateCommand();
cmd.CommandText = #"select * from print_spooler where spoolername = #ParamPrinterName";
cmd.Parameters.Add(new OracleParameter("#ParamPrinterName", printerName));
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
colValues.Add(reader["id"] + ";" + reader["id2"] + ";" + reader["id3"]);
}
con.Dispose();
reader.Dispose();
return colValues;
}
catch (Exception ex)
{
Console.WriteLine("Error : {0}", ex);
return null;
}
}
Here is a better view on the changes (If I am correct the 2nd not working optin is better to use because of SQL injection).

Related

Changes are not saved to the SQL Server database

The code compiles fine without error or warning, but the database does not change. I mean the changes are not saved to the database.
I wrote the following methods:
private void Test2()
{
connection = new SqlConnection();
string Conn = #"Data Source=(LocalDB)\MSSQLLocalDB;"
+ #"AttachDbFilename=|DataDirectory|\User.mdf;"
+ "Integrated Security=True;"
+ "Connect Timeout=30";
// string sqlString = Properties.Settings.Default.ConnectionString;
SqlConnection sqlConnection = new SqlConnection(Conn);
try
{
string SQL = "UPDATE Primuser SET Following = #Following WHERE Insta = #Insta";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.AddWithValue("#Following", "123");
sqlCommand.Parameters.AddWithValue("#Insta", "hgd");
sqlCommand.CommandText = SQL;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
MessageBox.Show("Record Updated");
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
and in this Code, the result is bigger than 0.
private void Test2()
{
connection = new SqlConnection();
connection.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;"
+ #"AttachDbFilename=|DataDirectory|\User.mdf;"
+ "Integrated Security=True;"
+ "Connect Timeout=30";
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT * FROM Primuser";
command.Connection = connection;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
DataSet dataset = new DataSet();
adapter.Fill(dataset, "Primuser");
foreach (DataRow row in dataset.Tables["Primuser"].Rows)
{
if (row["Insta"].ToString() == "1495")
{
row["Following"] = "1024";
}
}
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
try
{
var result = adapter.Update(dataset, "Primuser");
if (result > 0)
MessageBox.Show("Update Successful.");
else
MessageBox.Show("Update Failed.");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
but the database does not get changed. There are no errors and other query is working. I can insert, delete or select, but update is not working.

Insert in c# using npgsql

When I'm trying to execute an insert query with npgsqlcommand to postgres in c#, the execution of the program is suspend to cmd.ExecuteNonQuery();
Here's my code
public void Insert(Mouvement mvt)
{
NpgsqlConnection conn = null;
NpgsqlCommand cmd = null;
try
{
conn = UtilDB.GetConnection();
String sql = "INSERT INTO MOUVEMENT(ID_AERONEF,ID_PF,ID_ESCALE,DATE,SENS,NVOL,PISTE,BLOC,PAXC,PAXY,PAXBB,PAXEXO," +
"TRANSITDIRECT,TRANSITRI,TRANSITRRLC,CONTINU,PN,FRETPAYANT,FRETGRATUIT,BAGAGE,POSTE,MODE,BALISAGE,OBSERVATION) "+
"VALUES (:id_aeronef,:id_pf,:id_escale,:date,:sens,:nvol,:piste,:bloc,:paxc,:paxy,:paxbb,:paxexo," +
":transitdirect,:transitri,:transitrrlc,:continu,:pn,:fretpayant,:fretgratuit,:bagage,:poste,:mode,:balisage,:observation)";
conn.Open();
cmd = new NpgsqlCommand(sql, conn);
cmd.Parameters.Add("id_aeronef", mvt.Aeronef.Id);
cmd.Parameters.Add("id_pf", mvt.Plateforme.Id);
cmd.Parameters.Add("id_escale", mvt.Escale.Id);
cmd.Parameters.Add("date", mvt.Date);
cmd.Parameters.Add("sens", mvt.Sens);
cmd.Parameters.Add("nvol", mvt.Nvol);
cmd.Parameters.Add("piste", mvt.Piste);
cmd.Parameters.Add("bloc", mvt.Bloc);
cmd.Parameters.Add("paxc", mvt.PaxC);
cmd.Parameters.Add("paxy", mvt.PaxY);
cmd.Parameters.Add("paxbb", mvt.PaxBB);
cmd.Parameters.Add("paxexo", mvt.PaxExo);
cmd.Parameters.Add("transitdirect", mvt.TransitDirect);
cmd.Parameters.Add("transitri", mvt.TransitRI);
cmd.Parameters.Add("transitrrlc", mvt.TransitRRLC);
cmd.Parameters.Add("continu", mvt.Continu);
cmd.Parameters.Add("pn", mvt.Pn);
cmd.Parameters.Add("fretpayant", mvt.FretPayant);
cmd.Parameters.Add("fretgratuit", mvt.FretGratuit);
cmd.Parameters.Add("bagage", mvt.Bagage);
cmd.Parameters.Add("poste", mvt.Poste);
cmd.Parameters.Add("mode", mvt.Mode);
cmd.Parameters.Add("balisage", mvt.Balisage);
cmd.Parameters.Add("observation", mvt.Observation);
cmd.Prepare();
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if(cmd!=null) cmd.Dispose();
if(conn!=null) conn.Close();
}
}
Finally, it was a problem of type: I have character(1) in database but String(10) in C#

mysql query not working

I am trying to write a MySQL query in C# as below,I don't see any errors but neither I see the required output, the query works fine in mysqlworkbench ,am using MySql.Data.dll connection 6.9.9,what am I missing?how to debug what is wrong?
string connectionString = "server=10.xx.xxx.xx;database=databasename;uid=username;pwd=password;";
var conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = connectionString;
try
{
Console.WriteLine("Connecting to MySQL...");
conn.Open();
string sql = "select bb.version,bb.baat,bb.au from build bb where bb.version='x.xxx' and bb.state='COMPLETE'";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0] + " -- " + rdr[1]);
Console.ReadLine();
}
rdr.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
try to change:
from rdr[0]
to:
rdr.GetString(0)

winforms C# using sql server 2008

private void fillcode()
{
try
{
SqlConnection con = new SqlConnection("Data Source=ANISH;Initial Catalog=HM;Integrated Security=True");
con.Open();
string s = "select max(CustomerId) as Id from CustomerDetails";
SqlCommand cmd = new SqlCommand(s, con);
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
int i = Convert.ToInt16(dr["Id"].ToString());
sid.Text = (i + 1).ToString();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I am using this code, but there is a problem if there is no data in my table it will not accept.
So I want to use if no data is present it should take CustomerId as 1
It will be NULL of there are no rows so you can:
"select isnull(max(CustomerId), 1) as Id from CustomerDetails"
You should also look at ExecuteScalar which is designed for a singe result.
Try like this
private void fillcode()
{
try
{
SqlConnection con = new SqlConnection("Data Source=ANISH;Initial Catalog=HM;Integrated Security=True");
con.Open();
string s = "select max(CustomerId) as Id from CustomerDetails";
SqlCommand cmd = new SqlCommand(s, con);
SqlDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
int i = Convert.ToInt16(dr["Id"].ToString());
sid.Text = (i + 1).ToString();
}
else
{
sid.Text = "1"
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Avoid sql injection with calling function

I try to call function to select data from database,coz it will more efficient and i don't like to open connection and execute reader every time,have any solution can do like that?
this is my first method to select data from database,but will hit sql injection problem
protected void Button1_Click(object sender, EventArgs e)
{
Class1 myClass = new Class1();
lblAns.Text = myClass.getdata("Table1", "Student", "Student = '" + TextBox1.Text + "'");
}
public string getdata(string table,string field,string condition)
{
SqlDataReader rdr;
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");
string sql = "select " + field + " from " + table + " where " + condition;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
return "true";
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
finally
{
conn.Close();
}
return "false";
}
this is my second method but will hit error (ExecuteReader requires an open and available Connection. The connection's current state is closed.) at line (rdr = cmd.ExecuteReader();)
public string getdata(SqlCommand command,SqlConnection conn)
{
SqlDataReader rdr;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd = command;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
return "true";
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Select Error:";
msg += ex.Message;
}
finally
{
conn.Close();
}
return "false";
}
public SqlConnection conn()
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");
return conn;
}
protected void Button1_Click(object sender, EventArgs e)
{
Class1 myClass = new Class1();
string strSql;
strSql = "Select student from Table1 where student=#stu";
SqlCommand command = new SqlCommand(strSql, myClass.conn());
command.Parameters.AddWithValue("#stu", TextBox1.Text);
myClass.getdata(command, myClass.conn());
}
have solution can use 1st method but will not hit the sql injection problem?
Use ALWAYS the second solution. The only way to avoid Sql Injection is through the use of parameterized queries.
Also fix the error on the second example. You don't associate the connection to the command, also it is a bad practice to keep a global object for the connection. In ADO.NET exist the concept of Connection Pooling that avoid the costly open/close of the connection while maintaining a safe Handling of these objects
public string getdata(SqlCommand command)
{
// Using statement to be sure to dispose the connection
using(SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
cmd.Connection = conn;
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
return "true";
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Select Error:";
msg += ex.Message;
return msg;
}
}
return "false";
}

Categories

Resources