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).
I tried the following in SQL Server Management Studio; I can connect and run query, but not from my project
string s = "Server=LAPTOP-7J47C5JA\SQLEXPRESS;Database=Test;Trusted_Connection=True;";
string queryString = "SELECT * from tbclienti";
cn = new SQLConnection(s);
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(queryString, cn);
cn.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Text = reader[0].ToString();
label1.Text = reader[1].ToString()+ " " + reader[2].ToString();
}
reader.Close();
cn.Close();
I posted here whole code what could look like. Try it now.
string s = #"Server=(local)\SQLEXPRESS;Database=Test;Integrated Security=SSPI;";
using(SqlConnection cn = new SqlConnection(s))
{
string queryString = "SELECT * from tbclienti";
try
{
cn.Open();
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(queryString, cn);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Text = reader[0].ToString();
label1.Text = reader[1].ToString()+ " " + reader[2].ToString();
}
reader.Close();
}
catch(Exception ex)
{
// see if error appear
}
finally
{
cn.Close();
}
}
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#
Well, I work little bit with C # and I'm starting to work with Database with C # now, I've googled in several places and I am unable to identify where it is wrong, everywhere say I need to open a connection, but it is already open .
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=C:\Users\Gustavo\Documents\Visual Studio 2013\Projects\hour\hour\Database1.mdf");
con.Open();
try
{
string query = "INSERT INTO [Table] (name, time) VALUES ('test',1)";
SqlCommand cmd = new SqlCommand(query);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Use using, takes care of the closing and disposal for you just in case you forget to do it explicitly. Put it inside the try, you have the connection open command outside the try so it wont catch any connection error. You probably want to look at parameterizing your command too.
using (SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=C:\Users\Gustavo\Documents\Visual Studio 2013\Projects\hour\hour\Database1.mdf"))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO [Table] (name, time) VALUES (#name,#time)", conn))
{
cmd.Parameters.AddWithValue("#name", "test");
cmd.Parameters.AddWithValue("#time", 1);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=C:\Users\Gustavo\Documents\Visual Studio 2013\Projects\hour\hour\Database1.mdf");
try
{
string query = "INSERT INTO [Table] (name, time) VALUES ('test',1)";
SqlCommand cmd = new SqlCommand(query,con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
you need to assign the command to the connection. eg:
private static void ReadOrderData(string connectionString)
{
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
//----
SqlCommand command = new SqlCommand(
queryString, connection);
//----
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
}
I have written some C# to update a MySql table but I get an exception every time I call the method ExecuteNonQuery(). I have researched this on the web and every solution I find produces the same error. I have an open connection to the database and the update query to the database is written correctly. The code that I have so far come up with is :
public int executeUpdate()
{
int result = 0;
if (isConnected)
{
try
{
MySqlConnection cn = new MySqlConnection(connection.ConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = cn;
cmd.CommandText = "UPDATE test SET status_id = 1 WHERE test_id = 1";
int numRowsUpdated = cmd.ExecuteNonQuery();
}
catch (MySqlException exSql)
{
Console.Error.WriteLine("Error - SafeMySql: SQL Exception: " + query);
Console.Error.WriteLine(exSql.StackTrace);
}
catch (Exception ex)
{
Console.Error.WriteLine("Error - SafeMySql: Exception: " + query);
Console.Error.WriteLine(ex.StackTrace);
}
}
else
Console.Error.WriteLine("Error - SafeMySql: executeQuery failed. Not connected to DB");
}
Change your try section to the code below:
try
{
using(MySqlConnection cn = new MySqlConnection(connection.ConnectionString))
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = cn;
cmd.CommandText = "UPDATE test SET status_id = 1 WHERE test_id = 1";
cn.Open();
int numRowsUpdated = cmd.ExecuteNonQuery();
cmd.Dispose();
}
}
The connection must be opened before you execute a command. In the example above the command object will immediately be disposed and the connection object will implcitly be closed and disposed when you leave the using section.
I don't see the connection being opened.
Here is an example from MSDN: even inside a using block, they open the connection explicitly
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
Edit: The principle is the same for MySQL as it is for SQL Server:
public void CreateMySqlCommand(string myExecuteQuery, MySqlConnection myConnection)
{
MySqlCommand myCommand = new MySqlCommand(myExecuteQuery, myConnection);
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}