Error Import Database mdb into Sql Server - c#

Hello I have an error on this c# code,I have an exception on code: MessageBox.Show("Salto sulla query 3 "+ex), but I can not understand why, I loaded the exception image that is generated below,can you help me thanks.
MessageBox.Show("Aggiorno Articoli ");
//APRO LA CONNESSIONE AL FILE
dbConn = new OleDbConnection(#"Provider = Microsoft.Jet.OLEDB.4.0; Data Source=" + dialog.FileName + "; Persist Security Info = False; Jet OLEDB:Database Password = " + textBoxPwdComet.Text + "; Mode = Share Deny None");
//APRO LA CONNESSIONE
SqlConnection conn = db.apriconnessione();
//CREO LA TABELLA TEMPORANEA
String QueryTemp = "CREATE TABLE TabellaTemp(CODMARCA varchar(MAX),CODART varchar(MAX),DESCR varchar(MAX),UM varchar(MAX),PRZNETTO money,PRZCASA money,DATAAGG datetime,);";
SqlCommand cmdTemp = new SqlCommand(QueryTemp, conn);
cmdTemp.ExecuteNonQuery();
//COPIA DEI DATI NELLA TABELLA TEMPORANEA
string query = "SELECT CODMARCA,CODART,DESCR,UM,PRZNETTO,PRZCASA,DATAAGG FROM ARTICOLI";
OleDbDataAdapter da = new OleDbDataAdapter(query, dbConn);
DataTable dt = new DataTable();
da.Fill(dt);
SqlBulkCopy bulk = new SqlBulkCopy(conn);
bulk.DestinationTableName = "TabellaTemp";
bulk.WriteToServer(dt);
//Setto tutti gli articoli come non disponbili(QUELLI COMET)
try
{
String Query2 = "Update Articolo set Stato = 'Nondisponibile' where Importato = 'COMET' ";
cmdTemp = new SqlCommand(Query2, conn);
cmdTemp.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show("Salto su query 2");
}
//Aggiorno gli articoli, quelli che non vengono aggiornati non sono più disponbili
try {
String Query3 = "Update Articolo set Articolo.Stato = 'Disponibile',Articolo.Prezzo = TabellaTemp.PRZNETTO,Articolo.PrezzoListino = TabellaTemp.PRZCASA,Articolo.DataAggiornamento = TabellaTemp.DATAAGG,Articolo.Descrizione = TabellaTemp.DESCR,Articolo.UM = TabellaTemp.UM from Articolo inner join TabellaTemp on TabellaTemp.CodMarca = Articolo.CodMarca and TabellaTemp.CODART = Articolo.CodArt where Articolo.Importato = 'COMET' ";
cmdTemp = new SqlCommand(Query3, conn);
cmdTemp.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show("Salto sulla query 3 "+ex);
}
//FINE COPIA DATI TABELLA TEMPORANEA
//ELIMINO LA TABELLA TEMPORANEA
QueryTemp = "DROP TABLE TabellaTemp";
cmdTemp = new SqlCommand(QueryTemp, conn);
cmdTemp.ExecuteNonQuery();
//FINE
conn.Close();
MessageBox.Show("Aggiornamento Articoli terminato!! ");
CaricamentoDataGridNonDisponbili();
Exception:

Your query is timing out ie: not completing in default 30 second. Setting the CommandTimeout to higher value is not a good practice. To actually fix this, you need to provide the table schema (indexing if any) for all the table involved. Based on that you need to optimize your query to run faster using proper indexing.

First try setting your command object to nothing.
cmdTemp = Nothing;
If that doesn't fix it, then try investigating why your update query for query 3 is timing out. I would first convert your UPDATE statement into a SELECT statement. Verify that you are getting results, and that you aren't taxing the server with your query.
SELECT a.Stato, a.Prezzo, a.PrezzoListino, a.DataAggiornamento, a.Descrizione, a.UM,
t.PRZNETTO, t.PRZCASA, t.DATAAGG, t.DESCR, t.UM
FROM Articolo a
INNER JOIN TabellaTemp t on t.CodMarca = a.CodMarca
and t.CODART = a.CodArt
WHERE a.Importato = 'COMET'
If your SELECT statement is working properly, then I'm betting your UPDATE needs more time to run. I believe the timeout property for your command is 30 seconds. You could default this to 0 to run for as long as you wanted, but I would be careful on doing that. Try toying around with the timeout statement. This should fix things up for you.
String Query3 = "Update Articolo set Articolo.Stato = 'Disponibile',Articolo.Prezzo = TabellaTemp.PRZNETTO,Articolo.PrezzoListino = TabellaTemp.PRZCASA,Articolo.DataAggiornamento = TabellaTemp.DATAAGG,Articolo.Descrizione = TabellaTemp.DESCR,Articolo.UM = TabellaTemp.UM from Articolo inner join TabellaTemp on TabellaTemp.CodMarca = Articolo.CodMarca and TabellaTemp.CODART = Articolo.CodArt where Articolo.Importato = 'COMET' ";
cmdTemp = Nothing;
cmdTemp = new SqlCommand(Query3, conn);
// Setting command timeout to 2 minutes
cmdTemp.CommandTimeout = 120;
cmdTemp.ExecuteNonQuery();
I would honestly work on getting your UPDATE statement running at a more optimal speed if this fixes things.

Related

simple update query doesn't work, but when i put it into database itself it does work

When i run my code in the debugger and I hover my mouse over the parameters they do have the right values in them. It just doesn't update my database but when I copy the query and put it into the database it works without a problem.
The parameter values are:
id = 7
omschrijving = douche muntjes
prijs = 0,5
catagorie = faciliteiten
I checked the connection tring by using an insert query and that does add records to my database. And There is an id with the value of 7 in the database.
When I run a insert query or a delete query through my C# code it does work it's just the update statement that doesn't work. If anyone sees the issue please help me.
public static void wijzigprijs(int id, string omschrijving, decimal prijs, string catagorie)
{
try
{
try
{
OleDbConnection verbinding = new OleDbConnection(
#"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=..\..\..\La_Rustique.accdb;
Persist Security Info=False;");
verbinding.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
OleDbCommand query = new OleDbCommand();
query.CommandText = #"UPDATE prijslijst
SET omschrijving = #omschrijving,
prijs = #prijs,
catagorie = #catagorie
WHERE id = #id";
query.Parameters.Add(new OleDbParameter("#id", OleDbType.Integer));
query.Parameters["#id"].Value = id;
query.Parameters.Add(new OleDbParameter("#omschrijving", OleDbType.VarChar));
query.Parameters["#omschrijving"].Value = omschrijving;
query.Parameters.Add(new OleDbParameter("#prijs", OleDbType.Decimal));
query.Parameters["#prijs"].Value = prijs;
query.Parameters.Add(new OleDbParameter("#catagorie", OleDbType.VarChar));
query.Parameters["#catagorie"].Value = catagorie;
query.Connection = verbinding;
query.ExecuteNonQuery();
MessageBox.Show("succesvol gewijzigd");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
verbinding.Close();
}
}
EDIT UPDATE
Look at this topic. Here he explains how you should use variables with OleDbCommand
Variables with OleDbCommand
This is how you typically will do it when using SQLCommand parameters:
I know this doesnt answer your questions quite, but when i use SQLCommand i use this code whenever i want to update or insert with variables:
string query = #"UPDATE prijslijst
SET omschrijving = #omschrijving,
prijs = #prijs,
catagorie = #catagorie
WHERE id = #id";
SqlCommand cmd = new SqlCommand(query, connDatabase);
cmd.Parameters.Add("#id", SqlDbType.integer).Value = 7;
cmd.ExecuteNonQuery();
connDatabase.Close();
So you should be able to do the samething. Hope this will help you.
I have never seen OleDB queries written in the above syntax.
To state it differently: OleDB simply does not use named parameters, it uses the position only.
Try to change your SQL statement like this:
query.CommandText = #"UPDATE prijslijst
SET omschrijving = ?,
prijs = ?,
catagorie = ?
WHERE id = ?";
and then add the parameters in sequence of above in the code
below that.

C# How to get all data in Oracle database

I have 21 tables in Oracle 11g, and I need to display them using JOIN clauses. But the query is too slow and throws an System.OutOfMemoryException
My current code:
try
{
//string ConString;
using (OracleConnection con = new OracleConnection(ConString))
{
//string query = "SELECT PAX.CREATION_DATE,PAX.PNR,PAX.PAX_NMBR,PAX.UPDATE_LEVEL_MOD,PAX.PAX_NAME,PAX.CHANGE_OR_CANCEL_IND,PAX_SEATS.LEG_NMBR,PAX_SEATS.INSTANCE_NMBR,pax_seats.ssr_cd,pax_seats.carrier_cd,pax_seats.seat_nmbr,pax_seats.previous_status_codes FROM PAX INNER JOIN PAX_SEATS ON PAX.PNR = PAX_SEATS.PNR";
string query1 = "SELECT PNR FROM HISTORY_LEGS";
string query2 = "SELECT PAX.CREATION_DATE,PAX.PNR,PAX.PAX_NMBR,PAX.UPDATE_LEVEL_MOD,PAX.PAX_NAME,PAX.CHANGE_OR_CANCEL_IND,PAX_SEATS.LEG_NMBR,PAX_SEATS.INSTANCE_NMBR,pax_seats.ssr_cd,pax_seats.carrier_cd,pax_seats.seat_nmbr,pax_seats.previous_status_codes,PAX_SSRS.SSR_NMBR,PAX_TKT.TKTNMBR,PAX_TKT.ISSUING_AIRLINE, PAX_TKT.ISSUING_OFFC_NMBR, PAX_TKT.ISSUING_COUNTER_CD, PAX_TKT.ISSUING_AGNT_NMBR, PAX_TKT.TKT_IND, PAX_TKT.TKT_STATUS, PAX_TKT.TARIFICATION_IND,PAX_TKT.S_IND,PAX_TKT.ISSUANCE_DATE FROM PAX INNER JOIN PAX_SEATS ON PAX.PNR = PAX_SEATS.PNR RIGHT JOIN PAX_SSRS ON PAX.PNR = PAX_SSRS.PNR RIGHT JOIN PAX_TKT ON PAX.PNR = PAX_TKT.PNR";
//string query4 = "SELECT * FROM PAX";
//string query3 = "SELECT PAX.PAX_NMBR,PAX.PAX_NAME,RES_LEGS.ARNK_IND,RES_LEGS.CARRIER_CD1,RES_LEGS.CARRIER_CD2,RES_LEGS.FLT_NMBR,RES_LEGS.CLASS_CD,RES_LEGS.DAY_OF_WEEK,RES_LEGS.FLT_DATE,RES_LEGS.LEG_ORIGIN_CD,RES_LEGS.LEG_DES_CD,RES_LEGS.CURRENT_STATUS_CD,RES_LEGS.NUMBER_IN_PARTY,RES_LEGS.DP_TIME,RES_LEGS.AR_TIME,RES_LEGS.DATE_CHANGE_IND,RES_LEGS.FLT_IRREGULARITY_IND,RES_LEGS.LEG_TXT,RES_LEGS.PREVIOUS_STATUS_CODES,RES_LEGS.MESSAGE FROM RES_LEGS INNER JOIN PAX ON RES_LEGS.PNR = PAX.PNR";
OracleCommand cmd = new OracleCommand(query2, con);
OracleDataAdapter oda = new OracleDataAdapter(cmd);
DataSet ds = new DataSet();
oda.Fill(ds);
//dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing;
//dataGridView1.RowHeadersVisible = false;
if (ds.Tables.Count > 0)
{
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Questions:
How to get all data?
How to prevent System.OutofMemory?
How to speed up query execution performance?
You can look at indexes on your key fields to speed up the query a bit perhaps, but if you are getting a lot of rows back you'll be hitting some memory caps somewhere.
If you can, I would suggest implementing some paging: Paging with Oracle.
This will let you bring back smaller chunks of your data making it quicker and less likely to hit any memory limits.

Error "There is already an open DataReader associated with this Command which must be closed first" when using 2 distinct commands

I have this legacy code :
private void conecta()
{
if (conexao.State == ConnectionState.Closed)
conexao.Open();
}
public List<string[]> get_dados_historico_verificacao_email_WEB(string email)
{
List<string[]> historicos = new List<string[]>();
conecta();
sql =
#"SELECT *
FROM historico_verificacao_email
WHERE nm_email = '" + email + #"'
ORDER BY dt_verificacao_email DESC, hr_verificacao_email DESC";
com = new SqlCommand(sql, conexao);
SqlDataReader dr = com.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
string[] dados_historico = new string[6];
dados_historico[0] = dr["nm_email"].ToString();
dados_historico[1] = dr["dt_verificacao_email"].ToString();
dados_historico[1] = dados_historico[1].Substring(0, 10);
dados_historico[2] = dr["hr_verificacao_email"].ToString();
dados_historico[3] = dr["ds_tipo_verificacao"].ToString();
sql =
#"SELECT COUNT(e.cd_historico_verificacao_email) QT
FROM emails_lidos e
WHERE e.cd_historico_verificacao_email =
'" + dr["cd_historico_verificacao_email"].ToString() + "'";
tipo_sql = "seleção";
conecta();
com2 = new SqlCommand(sql, conexao);
SqlDataReader dr3 = com2.ExecuteReader();
while (dr3.Read())
{
//quantidade de emails lidos naquela verificação
dados_historico[4] = dr3["QT"].ToString();
}
dr3.Close();
conexao.Close();
//login
dados_historico[5] = dr["cd_login_usuario"].ToString();
historicos.Add(dados_historico);
}
dr.Close();
}
else
{
dr.Close();
}
conexao.Close();
return historicos;
}
I have created two separates commands to correct the issue, but it still continues: "There is already an open DataReader associated with this Command which must be closed first".
An additional info: the same code is working in another app.
Just add the following in your connection string:
MultipleActiveResultSets=True;
The optimal solution could be to try to transform your solution into a form where you don't need to have two readers open at a time. Ideally it could be a single query. I don't have time to do that now.
If your problem is so special that you really need to have more readers open simultaneously, and your requirements allow not older than SQL Server 2005 DB backend, then the magic word is MARS (Multiple Active Result Sets). http://msdn.microsoft.com/en-us/library/ms345109%28v=SQL.90%29.aspx. Bob Vale's linked topic's solution shows how to enable it: specify MultipleActiveResultSets=true in your connection string. I just tell this as an interesting possibility, but you should rather transform your solution.
in order to avoid the mentioned SQL injection possibility, set the parameters to the SQLCommand itself instead of embedding them into the query string. The query string should only contain the references to the parameters what you pass into the SqlCommand.
You can get such a problem when you are two different commands on same connection - especially calling the second command in a loop. That is calling the second command for each record returned from the first command. If there are some 10,000 records returned by the first command, this issue will be more likely.
I used to avoid such a scenario by making it as a single command.. The first command returns all the required data and load it into a DataTable.
Note: MARS may be a solution - but it can be risky and many people dislike it.
Reference
What does "A severe error occurred on the current command. The results, if any, should be discarded." SQL Azure error mean?
Linq-To-Sql and MARS woes - A severe error occurred on the current command. The results, if any, should be discarded
Complex GROUP BY on DataTable
I suggest creating an additional connection for the second command, would solve it. Try to combine both queries in one query. Create a subquery for the count.
while (dr3.Read())
{
dados_historico[4] = dr3["QT"].ToString(); //quantidade de emails lidos naquela verificação
}
Why override the same value again and again?
if (dr3.Read())
{
dados_historico[4] = dr3["QT"].ToString(); //quantidade de emails lidos naquela verificação
}
Would be enough.
I bet the problem is being shown in this line
SqlDataReader dr3 = com2.ExecuteReader();
I suggest that you execute the first reader and do a dr.Close(); and the iterate historicos, with another loop, performing the com2.ExecuteReader().
public List<string[]> get_dados_historico_verificacao_email_WEB(string email)
{
List<string[]> historicos = new List<string[]>();
conecta();
sql = "SELECT * FROM historico_verificacao_email WHERE nm_email = '" + email + "' ORDER BY dt_verificacao_email DESC, hr_verificacao_email DESC";
com = new SqlCommand(sql, conexao);
SqlDataReader dr = com.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
string[] dados_historico = new string[6];
dados_historico[0] = dr["nm_email"].ToString();
dados_historico[1] = dr["dt_verificacao_email"].ToString();
dados_historico[1] = dados_historico[1].Substring(0, 10);
//System.Windows.Forms.MessageBox.Show(dados_historico[1]);
dados_historico[2] = dr["hr_verificacao_email"].ToString();
dados_historico[3] = dr["ds_tipo_verificacao"].ToString();
dados_historico[5] = dr["cd_login_usuario"].ToString();
historicos.Add(dados_historico);
}
dr.Close();
sql = "SELECT COUNT(e.cd_historico_verificacao_email) QT FROM emails_lidos e WHERE e.cd_historico_verificacao_email = '" + dr["cd_historico_verificacao_email"].ToString() + "'";
tipo_sql = "seleção";
com2 = new SqlCommand(sql, conexao);
for(int i = 0 ; i < historicos.Count() ; i++)
{
SqlDataReader dr3 = com2.ExecuteReader();
while (dr3.Read())
{
historicos[i][4] = dr3["QT"].ToString(); //quantidade de emails lidos naquela verificação
}
dr3.Close();
}
}
return historicos;
Add MultipleActiveResultSets=true to the provider part of your connection string. See the example below:
<add name="DbContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=dbName;Persist Security Info=True;User ID=userName;Password=password;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
Try to combine the query, it will run much faster than executing an additional query per row.
Ik don't like the string[] you're using, i would create a class for holding the information.
public List<string[]> get_dados_historico_verificacao_email_WEB(string email)
{
List<string[]> historicos = new List<string[]>();
using (SqlConnection conexao = new SqlConnection("ConnectionString"))
{
string sql =
#"SELECT *,
( SELECT COUNT(e.cd_historico_verificacao_email)
FROM emails_lidos e
WHERE e.cd_historico_verificacao_email = a.nm_email ) QT
FROM historico_verificacao_email a
WHERE nm_email = #email
ORDER BY dt_verificacao_email DESC,
hr_verificacao_email DESC";
using (SqlCommand com = new SqlCommand(sql, conexao))
{
com.Parameters.Add("email", SqlDbType.VarChar).Value = email;
SqlDataReader dr = com.ExecuteReader();
while (dr.Read())
{
string[] dados_historico = new string[6];
dados_historico[0] = dr["nm_email"].ToString();
dados_historico[1] = dr["dt_verificacao_email"].ToString();
dados_historico[1] = dados_historico[1].Substring(0, 10);
//System.Windows.Forms.MessageBox.Show(dados_historico[1]);
dados_historico[2] = dr["hr_verificacao_email"].ToString();
dados_historico[3] = dr["ds_tipo_verificacao"].ToString();
dados_historico[4] = dr["QT"].ToString();
dados_historico[5] = dr["cd_login_usuario"].ToString();
historicos.Add(dados_historico);
}
}
}
return historicos;
}
Untested, but maybee gives some idea.

how to reference columns in sql server connection in C#

I'm trying to translate some perl code into C# and I'm having some trouble with the following.
After establishing a sql server connection and executing the select statement, how do I reference the different elements in the table columns. For example, in Perl it looks like:
my $dbh = DBI -> connect( NAME, USR, PWD )
or die "Failed to connect to database: " . DBI->message;
my $dbname = DB_NAME;
my $dbschema = DB_SCHEMA;
my $sql = qq{select a,b,c,d,e,f,g,h,i,...
from $dbname.$dbschema.package p
join $dbname.$dbschema.package_download pd on p.package_id = pd.package_id
join $dbname.$dbschema.download d on pd.download_id = d.download_id
where p.package_name = '$package'
--and ds.server_address like 'tcp/ip'
order by a,b,c,d,..};
my $sth = $dbh -> prepare( $sql )
or die "Failed to prepare statement: " . $dbh->message;
$sth -> execute()
or die "Failed to execute statement: " . $sth->message;
#now to go through each row in result table
while ( #data = $sth->fetchrow_array() )
{
print "$data[0]";
# If source server FTP is not already open, make new FTP
if ( $data[0] != $src_id )
{
if ( $src_ftp )
{ $src_ftp -> quit; }
$src_ftp = make_ftp( $data[1], $data[2], $data[3], $data[18], $data[19], $data[20] );
$src_id = $data[0];
}
}
so far I've got it down to
string db = NAME;
string myConnectionString = "Data Source=ServerName;" + "Initial Catalog=" + db + "User id=" + ODBC_USR + "Password=" + PWD
SqlConnection myConnection = new SqlConnection(myConnectionString);
string myInsertQuery = "select a,b,c,d,e,f,g,h,i,...
from $dbname.$dbschema.package p
join $dbname.$dbschema.package_download pd on p.package_id = pd.package_id
join $dbname.$dbschema.download d on pd.download_id = d.download_id
where p.package_name = '$package'
--and ds.server_address like 'tcp/ip'
order by a,b,c,d,..";
SqlCommand myCommand = new SqlCommand(myInsertQuery);
myCommand.Connection = myConnection;
myConnection.Open();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
but how do I reference the columns like data[0] and data[1] in C#. Sorry I'm new to both languages so my background is severely lacking. Thanks!
You could reference your column directly by its column name or by numeric order (it starts with 0 as the first column) either through a DataTable, DataSet, DataReader or a specific DataRow.
For the sake of example i'll use a DataTable here and I will name it as dt and let's say we want to reference the first row then you could reference it with the following Syntax/Format:
dt[RowNumber]["ColumnName or Column Number"].ToString();
For example:
dt[0]["a"].ToString();
Or by number the first column with be 0 like:
dt[0][0].ToString();
And use Parameters by the way because without which it would be susceptible to SQL Injection. Here's a more complete code below:
string db = NAME;
string myConnectionString = "Data Source=ServerName;" + "Initial Catalog=" + db + "User id=" + ODBC_USR + "Password=" + PWD
using (SqlConnection connection = new SqlConnection(myConnectionString))
{
string mySelectQuery = #"SELECT a,b,c,d,e,f,g,h,i,...
FROM package p
JOIN package_download pd on p.package_id = pd.package_id
join download d on pd.download_id = d.download_id
WHERE p.package_name = #PackageName
AND ds.server_address LIKE 'tcp/ip%'
ORDER by a,b,c,d";
try
{
connection.Open();
using (SqlDataAdapter da = new SqlDataAdapter(mySelectQuery, connection))
{
using (SqlCommand cmd = new SqlCommand())
{
da.SelectCommand.Parameters.AddWithValue("#PackageName", txtPackage.Text);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count>0) // Make sure there is something in your DataTable
{
String aVal = dt[0]["a"].ToString();
String bVal = dt[0]["b"].ToString();
// You'll be the one to fill up
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I change your LIKE 'tcp/ip' to LIKE 'tcp/ip%' by the way which is the more appropriate one of using LIKE.
you can use ado.net entity data table to reference the tables in your sql server. I don't know if you're asking exactly this but it may help. because direct referencing to sql server is not possible as far as i know.

get the protein that contains specific sequence using OLEDB

Here is a background on my program: each protein is made from a sequence of amino acids(or AA)
I have some tables :tblProInfo(that contains general info about proteins),tblOrderAA(that contains the sequence(AA sequence) of specific protein(for each protein there is a serial number that i set before))
now, I'm trying to retvive the science names of the protein that contains part of sequence that the user put in textbox1. It is likely that more than one protein contains the sequence that the user typed.
Here is my code. I got "Syntax error" and I'm sure I have more mistakes.Please HELP me!
public void OpenDB()
{
dataConnection = new OleDbConnection();
try
{
dataConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Projects_2012\\Project_Noam\\Access\\myProject.accdb";
dataConnection.Open();
}
catch (Exception e)
{
MessageBox.Show("Error accessing the database: " +
e.Message,
"Errors",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private string FromCodonsToProtein(string codons)
{
OpenDB();
int sizePro=0, i,counter=0,serialPro;
string st="",tempst="";
OleDbCommand datacommand = new OleDbCommand();
datacommand.Connection = dataConnection;
datacommand.CommandText = "SELECT tblProInfo.proInfoAAnum, tblProInfo.proInfoSerialNum,tblProInfo.proInfoScienceName FROM tblProInfo";
OleDbDataReader dataReader = datacommand.ExecuteReader();
while(dataReader.Read())
{
sizePro = dataReader.GetInt32(counter);
serialPro= dataReader.GetInt32(counter+1);
counter++;
OleDbCommand cmd= new OleDbCommand();
cmd.Connection = dataConnection;
cmd.CommandText = "SELECT tblOrderAA.orderAACodon1 FROM tblOrderAA"
+"WHERE (((tblOrderAA.orderAASerialPro)='"+serialPro+"'))";
OleDbDataReader rdr = cmd.ExecuteReader();
tempst="";
for (i = 0; i > sizePro; i++)
{
tempst = tempst + rdr.GetString(i);
}
if (tempst.Contains(codons))
{
st = st + " \n" + dataReader.GetString(counter);
}
}
return st;
}
Missing a space here
cmd.CommandText = "SELECT tblOrderAA.orderAACodon1 FROM tblOrderAA"
+"WHERE (((tblOrderAA.orderAASerialPro)='"+serialPro+"'))";
rewrite in this way
cmd.CommandText = "SELECT tblOrderAA.orderAACodon1 FROM tblOrderAA"
+" WHERE (((tblOrderAA.orderAASerialPro)='"+serialPro+"'))";
// ^ here
However you should use parametrized query (also with msaccess) to avoid possible errors and injection attacks.
Another problem is the global dataConnection. Don't do that, you gain nothing in this way.
Return the connection and encapsulate it with a using statement.
For example:
public OleDbConnection OpenDB()
{
dataConnection = new OleDbConnection();
dataConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Projects_2012\\Project_Noam\\Access\\myProject.accdb";
dataConnection.Open();
return dataConnection;
}
then in the calling code use this syntax
using(OleDbConnection cnn = OpenDB())
{
// in the rest of your code, replace dataConnection with cnn
// The using statement will ensure that in the case of exceptions
// your connection will be allways closed and properly disposed
........
}
EDIT: Can't give you a full working solutions, too many aspects of your problem are unknown to me, however a great simplification will be to change your query in this way
SELECT DISTINCT
tblProInfo.proInfoAAnum,
tblProInfo.proInfoSerialNum,
tblProInfo.proInfoScienceName
FROM tblProInfo LEFT JOIN tblOrderAA
ON tblOrderAA.orderAASerialPro = tblProInfo.proInfoSerialNum
WHERE tblOrderAA.orderAACodon1 = #codons
Try it directly in access using its query editor, if it works as you expected then change your code. You don't need two query and crossed loops to get the results.

Categories

Resources