idb2 connection not allowed with c# - 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.

Related

ConnectionString Exception In Oracle database

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();

exception of duplicate key in my code

I have a Form that contains an "Add" button and a textBox, which is used to add information to a database table.
I need to check if the code entered in the TextBox is available before I can insert it.
My problem is that I get errors, as it attempts to add a "duplicate primary key" and I'm unsure of the source of error.
Below is the code I currently have:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection connection1 = new SqlConnection(connectionString);
connection1.Open();
String reqt1="select numero_cpte from compte where numero_cpte="+textBox1.Text+";";
SqlCommand sql1 = new SqlCommand(reqt1, connection1);
int d = int.Parse(textBox1.Text);
int dd = Convert.ToInt32(sql1.ExecuteScalar());
if(d == dd)
{
int o1 = sql1.ExecuteNonQuery();
MessageBox.Show("this account is not valide!!","Fiche ");
connection1.Close();
}
if (String.IsNullOrEmpty(textBox1.Text) == true)
{
MessageBox.Show("You should insert the code!!","Fiche",
MessageBoxButtons.OK,MessageBoxIcon.Information);
}
else
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand sql = new
SqlCommand("insert into compte values(" + textBox1.Text + ",'" +
textBox2.Text + "','" + type_cpteComboBox.SelectedItem.ToString() +
"','" + textBox2.Text + "','" + comboBox1.SelectedItem.ToString() +
"'," + comboBox2.SelectedItem.ToString() + ",'" +
checkBox1.Checked.ToString() + "','" + checkBox2.Checked.ToString() +
"','" +textBox5.Text+ "','" +textBox6.Text+ "');", connection);
int o = sql.ExecuteNonQuery();
MessageBox.Show(o + "Success of add","Fiche");
connection.Close();
textBox1.Text = "";
textBox2.Text = "";
}
This is the error I see:
The insert command works perfectly, but When I try to test if the code that I'am going to add in the base exists or not (by typing a code that I know exists), I get this exception.
It looks like your code drops down into the add code even if you have discovered that your number is a duplicate. Try adding "return;" after you close the connection.
MessageBox.Show("Ce compte existe.Veuillez sasir un numéro de compte valide!!", "Fiche Comptes");
connection1.Close();
return;
private object ExecuteScalar(string sql)
{
using (SqlConnection connection1 = new SqlConnection(connectionString))
{
connection1.Open();
SqlCommand sql1 = new SqlCommand(sql, connection1);
return sql1.ExecuteScalar();
}
}
The advantage of this is that you always know that your connection will be closed when you are done. Even if you are only going to be calling this method once, it improves readability and is therefore helpful.

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();
}
}

Parameters supplied for object which is not a function. If the parameters are intended as a table hint, a WITH keyword is required

I'm running Windows 7 and II7 and SQL server 2008 R2 . I have an aspx program and when I try to run it I get the following error
Parameters supplied for object 'users' which is not a function. If
the parameters are intended as a table hint, a WITH keyword is
required.
What I've coded is this :
public ArrayList GetGoodsList(string type, string goodsType, string user, string payType, bool flag)
{
conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["Conn"].ToString());
DataSet ds = new DataSet();
sSql = "select count(*) from users('" + type + "','" + goodsType + "','" + user + "','" + payType + "')";
if (flag == true)
{
sSql += "where IsCommend = 1";
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = sSql;
conn.Open();
int maxRow = Int32.Parse(cmd.ExecuteScalar().ToString());
sSql = "select * from users('" + type + "','" + goodsType + "','" + user + "','" + payType + "')";
if (flag == true)
{
sSql += "where IsCommend = 1";
}
cmd.CommandText = sSql;
SqlDataReader reader = cmd.ExecuteReader();
ArrayList gInfos = new ArrayList();
GoodsInfo gInfo;
for (int i = 0; i < maxRow; i++)
{
if (reader.Read())
{
gInfo = new GoodsInfo();
gInfo.G_ID = Int32.Parse(reader["G_ID"].ToString());
gInfo.G_Name = reader["G_Name"].ToString();
gInfo.Type = reader["Type"].ToString();
gInfo.GoodsType = reader["GoodsType"].ToString();
gInfos.Add(gInfo);
}
}
conn.Close();
return gInfos;
}
Any idea? Thanks!
Without giving away the answer, your issue in in your SELECT statement, sSql = ...
It's not the correct SQL syntax.
Have a read of this wikipedia article on the SELECT statement.

how to insert data if it contain apostrophe?

Actally my task is load csv file into sql server using c# so i have split it by comma my problem is that some field's data contain apostrop and i m firing insert query to load data into sql so its give error my coding like that
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
namespace tool
{
public partial class Form1 : Form
{
StreamReader reader;
SqlConnection con;
SqlCommand cmd;
int count = 0;
//int id=0;
FileStream fs;
string file = null;
string file_path = null;
SqlCommand sql_del = null;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog file1 = new OpenFileDialog();
file1.ShowDialog();
textBox1.Text = file1.FileName.ToString();
file = Path.GetFileName(textBox1.Text);
file_path = textBox1.Text;
fs = new FileStream(file_path, FileMode.Open, FileAccess.Read);
}
private void button2_Click(object sender, EventArgs e)
{
if (file != null )
{
sql_del = new SqlCommand("Delete From credit_debit1", con);
sql_del.ExecuteNonQuery();
reader = new StreamReader(file_path);
string line_content = null;
string[] items = new string[] { };
while ((line_content = reader.ReadLine()) != null)
{
if (count >=4680)
{
items = line_content.Split(',');
string region = items[0].Trim('"');
string station = items[1].Trim('"');
string ponumber = items[2].Trim('"');
string invoicenumber = items[3].Trim('"');
string invoicetype = items[4].Trim('"');
string filern = items[5].Trim('"');
string client = items[6].Trim('"');
string origin = items[7].Trim('"');
string destination = items[8].Trim('"');
string agingdate = items[9].Trim('"');
string activitydate = items[10].Trim('"');
if ((invoicenumber == "-") || (string.IsNullOrEmpty(invoicenumber)))
{
invoicenumber = "null";
}
else
{
invoicenumber = "'" + invoicenumber + "'";
}
if ((destination == "-") || (string.IsNullOrEmpty(destination)))
{
destination = "null";
}
else
{
destination = "'" + destination + "'";
}
string vendornumber = items[11].Trim('"');
string vendorname = items[12].Trim('"');
string vendorsite = items[13].Trim('"');
string vendorref = items[14].Trim('"');
string subaccount = items[15].Trim('"');
string osdaye = items[16].Trim('"');
string osaa = items[17].Trim('"');
string osda = items[18].Trim('"');
string our = items[19].Trim('"');
string squery = "INSERT INTO credit_debit1" +
"([id],[Region],[Station],[PONumber],[InvoiceNumber],[InvoiceType],[FileRefNumber],[Client],[Origin],[Destination], " +
"[AgingDate],[ActivityDate],[VendorNumber],[VendorName],[VendorSite],[VendorRef],[SubAccount],[OSDay],[OSAdvAmt],[OSDisbAmt], " +
"[OverUnderRecovery] ) " +
"VALUES " +
"('" + count + "','" + region + "','" + station + "','" + ponumber + "'," + invoicenumber + ",'" + invoicetype + "','" + filern + "','" + client + "','" + origin + "'," + destination + "," +
"'" + (string)agingdate.ToString() + "','" + (string)activitydate.ToString() + "','" + vendornumber + "',' " + vendorname + "',' " + vendorsite + "',' " + vendorref + "'," +
"'" + subaccount + "','" + osdaye + "','" + osaa + "','" + osda + "','" + our + "') ";
cmd = new SqlCommand(squery, con);
cmd.CommandTimeout = 1500;
cmd.ExecuteNonQuery();
}
label2.Text = count.ToString();
Application.DoEvents();
count++;
}
MessageBox.Show("Process completed");
}
else
{
MessageBox.Show("path select");
}
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=192.168.50.200;User ID=EGL_TEST;Password=TEST;Initial Catalog=EGL_TEST;");
con.Open();
}
}
}
vendername field contain data (MCCOLLISTER'S TRANSPORTATION) so how to pass this data
Use prepared statements, in this case SqlParameterCollection.AddWithValue or equivalent. There are a variety of tutorials available for this.
You are very naughty for building your sql statements that way, Santa Claus is definitely not going to visit you this year. Doing queries the way you are is opening yourself to sql injection attacks, intentional and unintentional as you've discovered with the '.
You should use parameterized query strings or stored procedures.
const string connString = "Data Source=localhost;Initial Catalog=OnlineQuiz;Integrated Security=True";
static void Main(string[] args)
{
string query = string.Format("SELECT * FROM [User] WHERE name like #name");
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("#name", "F%");
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader.GetValue(1));
}
}
}
}
}
You need to escape the apostrophe by adding a second apostrophe:
vendorname = vendorname.Replace("'", "''");
Disclaimer: Writing a raw SQL statement without using parameters is dangerous. Ideally, you should write a full SQL insert statement with assumed parameters, and instead of concatenating the value directly into the string, pass it in as a parameter:
string parameterizedSQL = "insert into credit_debit1 (id,region,station) values (#count, #region,#station)";
SqlCommand cmd = new SqlCommand(parameterizedSQL, con);
cmd.Parameters.Add("#count", SqlDbType.Int).Value = count;
cmd.Parameters.Add("#region", SqlDbType.VarChar).Value = region;
cmd.Parameters.Add("#station", SqlDbType.VarChar).Value = station;
cmd.ExecuteNonQuery();

Categories

Resources