ConnectionString Exception In Oracle database - c#

I want to insert some data into an Oracle database through a C# application.
I keep getting an exception which looks like this : "The ConnectionString has not been properly initialized".
The code for inserting is bellow:
try
{
conn.openConnection();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn.Connection;
cmd.CommandType = CommandType.Text;
String sqlCommand = "INSERT INTO ComandaDVD (Id_Comanda,Id_Format,Data_Comanda,Id_TipPlata,Pret) VALUES (" +
"'" + txt_idComanda.Text + "', " +
"'" + txtFormat.Text + "', " +
"to_date('" + txtData.Text + "', 'DD-MM-YYYY'), " +
"'" + txtIdTipPlata.Text + "', " +
"'" + txtPret.Text + "')";
cmd.CommandText = sqlCommand;
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("Comanda cu id_comanda[" + txt_idComanda.Text + "]a fost primita!");
}
else
{
MessageBox.Show("Eroare");
}
conn.closeConnection();
}
catch (Exception ex)
{
MessageBox.Show("Exceptie" + ex.Message);
}
}
I also made a personalized class to ease the connection handling:
class Conexiune_DB
{
private OracleConnection conn;
private static string CONNECTION_STRING = "Data Source=80.96.123.131/ora09;User Id=hr;Password=oracletest;";
public Conexiune_DB() { conn = new OracleConnection(CONNECTION_STRING); }
public void openConnection() { conn.Open(); }
public void closeConnection() { conn.Dispose(); }
public OracleConnection Connection
{
get { return conn; }
}
}
The exception appears to be because of 'conn.Open' in that class. Which is weird, because i made some insertions before, and i didn't have any problems.
Thanks in advance.

I'm quite sure this happens because you're opening your connection with conn.openConnection(); before you've even set a ConnectionString to it. So instead you should first set the ConnectionString to your conn before opening it. I'm not sure which connectionstring you'd like to use in this moment, but if it's the same, then just put conn.Conexiune_DB(); above conn.openConnection();

Related

idb2 connection not allowed with c#

i have a little problem with my connection with the AS400.I am using c#.
When i want to do an insert sql statement on a table, it pops this message
SystemInvalidOperationException : This operation cannot be successful
because the connection is not allowed at
IBM.Data.DB2.iSeries.iDB2Command.verifyConnection(); at
IBM.Data.DB2.iSeries.iDB2Command.ExecuteNonQuery();
here is my definition of the connection string
public static string userID;
public static string passwd;
public static string system;
public string query;
public iDB2Connection conn = new iDB2Connection("DataSource=" + system + ";UserID=" + userID + ";Password=" + passwd + ";DataCompression=true;");
and the code that contains the insert statement
public void insert(Programs prog, int nbfiche)
{
//conn.Open();
try
{
string sqlQuery = "INSERT INTO DIIAB.FICDET(MTPRO,MTFICH,MTPGM,MTNSRC,MTLSRC,MTTYP,MTOBJT) VALUES('" + Progiciel + "','" + nbfiche + "','" + prog.program_name +
"','" + prog.source_program + "','" + LIB + "','" + prog.element_type + "','" + prog.program_type + "')";
iDB2Command iDB2Command = conn.CreateCommand();
iDB2Command.CommandText = sqlQuery;
iDB2Command.ExecuteNonQuery();
sqlQuery = "select MTFICH from DIIAB.FICDET where MTFICH='" + nbfiche + "'";
iDB2Command command = conn.CreateCommand();
command.CommandText = sqlQuery;
iDB2DataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (reader[0].ToString().Contains(nbfiche.ToString()))
{
System.Windows.MessageBox.Show("Un programme à été rajouté à la fiche.");
}
}
System.Windows.MessageBox.Show("Les programmes ont été rajouté à la fiche", "Information");
}
catch (Exception e)
{
System.Windows.MessageBox.Show(e.ToString());
}
}
and the code that call the method insert with the parameters
edit.userID = userID;
edit.passwd = passwd;
edit.system = system;
edit editeur = new edit();
editeur.nbfiche = Convert.ToInt32(daoficnbr.fICNBR.nb_fiche);
editeur.fiche_status = Statuss.Text;
editeur.Progiciel = PRO.Text;
editeur.getpgm(arcad.lib,daoficnbr.fICNBR.nb_fiche);
foreach (Programs p in editeur.content)
{
editeur.insert(p, editeur.nbfiche);
}
Could help me please it's been already 2 days i am stuck on this one
Solution was to ensure that the connection string was terminated by a semi-colon and that the conn.Open() completed successfully before running commands or queries.

OleDb Exception

For 5 hour searching i can't find my mistake. I get this exception. What is wrong?
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in MyDictionary.exe
Additional information: Syntax error in INSERT INTO statement.
My code:
public void Insert(Word word)
{
string language=FindLanguage();
try
{
command.CommandText ="INSERT INTO "+language+" ( Native , Foreign , Definition , AddingDate) values ( '" + word.Native + "' , '" + word.Foreign + "' , '" + word.Definition + "' ,'" + word.AddingDate + "')";
command.CommandType = System.Data.CommandType.Text;
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (connection != null)
{
connection.Close();
}
}
}
You should use parameters in your insert statement.Also looks like you are missing command.Connection = connection;.
Note that your SQL is prone for SQL Injection
command.CommandText ="INSERT INTO "+language+"([Native],[Foreign],[Definition],[AddingDate]) VALUES (#Native,#Foreign,#Definition,#AddingDate)";
command.Parameters.AddWithValue("#Native", word.Native);
command.Parameters.AddWithValue("#Foreign",word.Foreign);
command.Parameters.AddWithValue("#Definition",word.Definition);
command.Parameters.AddWithValue("#AddingDate",word.AddingDate);
command.CommandType = System.Data.CommandType.Text;
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
In OleDb the correct syntax of the INSERT INTO statement involves usage of the SELECT clause even though you're appending static values. So you need to change your query like bellow example.
Further, don't construct try...catch..finally if you don't actually handle a raised exception. In the sake of disposal use using() { } block instead. So here it is:
public void Insert(Word word)
{
string language=FindLanguage();
using (var connection = new OleDbConnection("connection string goes here"))
using (var command = new OleDbCommand...)
{
command.CommandText = #
"INSERT INTO " + language + "(Native, Foreign, Definition, AddingDate)" +
"SELECT '"
+ word.Native + "' AS Native, '"
+ word.Foreign + "' AS Foreign, '"
+ word.Definition + "' AS Definition, '"
+ word.AddingDate + "' AS AddingDate"
;
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}

input string was not in a correct format c# datetimepicker

private void btnSave_Click(object sender, EventArgs e)
{
try
{
if (_action == "edit")
{
update(_id, int.Parse(cbSupplier.ValueMember), dtpTRXdate.Value.ToString("yyyy-MM-dd"), dtpDUEdate.Value.ToString("yyyy-MM-dd"), txtRemarks.Text.ToString(), _conn);
}
else
{
insert(int.Parse(cbSupplier.ValueMember), dtpTRXdate.Value.ToString("yyyy-MM-dd"), dtpDUEdate.Value.ToString("yyyy-MM-dd"), txtRemarks.Text.ToString(), _conn);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void insert(int sup_ID, string TRX_date, string DUE_date, string remarks, MySqlConnection conn)
{
MessageBox.Show(sup_ID.ToString() + " " + TRX_date + " " + DUE_date + " " + remarks);
MySqlCommand command = new MySqlCommand();
command.Connection = conn;
command.CommandText = "INSERT INTO PO_HEADER VALUES(null," + sup_ID + ",'" + TRX_date + "','" + DUE_date + "','" + remarks + "')";
command.ExecuteNonQuery();
}
public void update(int id, int sup_id, string trx_date, string due_date, string remarks, MySqlConnection conn)
{
MySqlCommand command = new MySqlCommand();
command.Connection = conn;
command.CommandText = "UPDATE PO_HEADER SET SUPPLIER_ID=" + sup_id + ", TRX_DATE='" + trx_date + "', DUE_DATE='" + due_date + "', REMARKS='" + remarks + "' WHERE ID=" + id;
command.ExecuteNonQuery();
}
dtpTRXdate it's datetimepicker
the problem at : dtpTRXdate.Value.ToString("yyyy-MM-dd") and dtpDUEdate.Value.ToString("yyyy-MM-dd")
when i click button save and run the function, it say "input string was not in a correct format"
i messagebox the string it's true, example : "2012-12-12"
have any idea???
Problem : You are sending the Date value selected from DateTimePicker control after converting into string as yyyy-MM-dd, but in database table the datatype might be Date so it takes Date and Time both.
Solution : you need to convert Date Selected from DateTimePicker control into into Date and Time instead of converting into Date only.
Try This:
dtpTRXdate.Value.ToString("yyyy-MM-dd HH:mm:ss")
Suggestion : by using parameterised queries you do not need to worry about the types being passed as it will be taken care by default.
by using parameterised queries you can avoid SQL Injection Attacks
Complete Code: using parameterised queries
private void btnSave_Click(object sender, EventArgs e)
{
try
{
if (_action == "edit")
{
update(_id, int.Parse(cbSupplier.ValueMember), dtpTRXdate.Value, dtpDUEdate.Value, txtRemarks.Text.ToString(), _conn);
}
else
{
insert(int.Parse(cbSupplier.ValueMember), dtpTRXdate.Value, dtpDUEdate.Value, txtRemarks.Text.ToString(), _conn);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void insert(int sup_ID, DateTime TRX_date, DateTime DUE_date, string remarks, MySqlConnection conn)
{
MessageBox.Show(sup_ID.ToString() + " " + TRX_date.ToShortDateSTring() + " " + DUE_date.ToShortDateSTring() + " " + remarks);
MySqlCommand command = new MySqlCommand();
command.Connection = conn;
command.CommandText = "INSERT INTO PO_HEADER VALUES(#value1,#sup_ID,#TRX_date,# DUE_date,#remarks)";
command.Parameters.AddWithValue("#value1",DBNull.Value);
command.Parameters.AddWithValue("#sup_ID",sup_ID);
command.Parameters.AddWithValue("#TRX_date",TRX_date);
command.Parameters.AddWithValue("#DUE_date",DUE_date);
command.Parameters.AddWithValue("#remarks",remarks);
command.ExecuteNonQuery();
}
public void update(int id, int sup_id, string trx_date, string due_date, string remarks, MySqlConnection conn)
{
MySqlCommand command = new MySqlCommand();
command.Connection = conn;
command.CommandText = "UPDATE PO_HEADER SET SUPPLIER_ID=#sup_id,TRX_DATE=#trx_date,DUE_DATE=#due_date,REMARKS=#remarks WHERE ID=#id";
command.Parameters.AddWithValue("#sup_ID",sup_ID);
command.Parameters.AddWithValue("#trx_date",trx_date);
command.Parameters.AddWithValue("#due_date",due_date);
command.Parameters.AddWithValue("#remarks",remarks);
command.Parameters.AddWithValue("#sup_ID",id);
command.ExecuteNonQuery();
}

C# to store data into MS-Access database

I need to write C# code to insert data into an MS-Access database. The program adds it but if I close the application the database resets.
database is in the debug x86 folder
Here is my code for adding data
provider = "Provider=Microsoft.ACE.OLEDB.12.0";
applicatiePad = Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf("\\"));
pad = "Data Source=" + applicatiePad + "/Geluidsfragmentendb.accdb";
connectionString = provider + ";" + pad;
connection = new OleDbConnection(connectionString);
...
public bool VoegToe(int geluidsfragmentnr,
string Titel,
string bestandsnaam,
int min,
int sec)
{
string time = min + ":" + sec;
DateTime tijd = Convert.ToDateTime(time);
String voegGfToe = "INSERT INTO Geluidsfragment (GeluidsfragmentID, Titel, bestandsnaam, tijdsduur) VALUES (" + geluidsfragmentnr + ",'" + Titel + "'" + ",'"+ bestandsnaam + "','" + tijd + "')";
OleDbCommand command = new OleDbCommand(voegGfToe, connection);
try
{
connection.Open();
command.ExecuteNonQuery();
return true;
}
catch ( Exception e)
{
MessageBox.Show(e.Message);
return false;
}
finally
{
connection.Close();
}
}

Exception give msg as :"IndexOutOfRangeException was unhandle OrgerView" in C#, What should I do?

I tried to connect MS Access Db in C# and want to View all.
My Db connection code is show in below
String conStr= #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Administrator\Desktop\SMSGateway2\SMS.mdb;Persist Security Info=True; Jet OLEDB:Database Password=testing" ;
OleDbConnection con;
con = new OleDbConnection(conStr);
string cmdString = "select * from Temp_Order";
OleDbCommand command = new OleDbCommand(cmdString, con);
try
{
con.Open();
command.ExecuteNonQuery();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
richTextBox1.Text = "Student Name: " + reader["SenderNo"].ToString() + "\n" +
"ID: " + reader["OrgerView"].ToString() + "\n" +
"Program: " + reader["OrderTime"].ToString() + "\n" +
"Address: " + reader["Flag"].ToString();
}
}
catch (Exception readexcp)
{
throw readexcp;
}
finally
{
con.Close();
}
First remove this line command.ExecuteNonQuery(); then check SenderNo, OrgerView, OrderTime and Flag are valid column names.

Categories

Resources