Error on Parameter C# SQL - c#

I need verify the Parameter RGP, PEIXE, DATA_REGISTRO for my method return true. But on PEIXE parameter this giving error:
Expects 'PEIXE' parameter, which was not provided.
PEIXE is a Varchar type on SQL, RGP is a Int type and DATA_REGISTRO is a Date type.
public bool Search_RGP_Cadastro(int param_RGP, string param_date, string param_peixe)
{
SqlDataReader objReader;
SqlCommand objcmd = null;
vsql = "SELECT [RGP], [PEIXE], [PESO], [QUANTIDADE], [DATA_REGISTRO] FROM cadastro WHERE RGP = #RGP and PEIXE = #PEIXE and DATA_REGISTRO = #DATA_REGISTRO";
if (this.Conectar())
{
try
{
DateTime dtParam = DateTime.Parse(param_date);
objcmd = new SqlCommand(vsql, objCon);
objcmd.Parameters.Add(new SqlParameter("#RGP", param_RGP));
objcmd.Parameters.Add(new SqlParameter("#PEIXE", param_peixe));
objcmd.Parameters.Add(new SqlParameter("#DATA_REGISTRO", dtParam));
objReader = objcmd.ExecuteReader();
if (objReader.Read())
{
valor.retorna_RGP = objReader.GetInt32(0);
valor.retorna_nome_peixe = objReader.GetString(1);
valor.retorna_peso = objReader.GetDouble(2);
valor.retorna_Quantidade = objReader.GetInt32(3);
valor.retorna_date_time = objReader.GetDateTime(4);
}
return true;
}
catch
{
throw;
}
finally
{
this.Desconectar();
}
}
else
return false;
}

I'd wrap your param_peixe in single quotes, like this:
objcmd.Parameters.Add(new SqlParameter("#PEIXE", "'" + param_peixe + "'"));
It wouldn't be the first time I've seen SQL reject the use of a string as a VARCHAR.

Related

how to return a count value with sqllite and c#

I am trying to see if a record exists using c# and sqllite..
My code is as follows
public static bool RecordExists(string fileName)
{
SetConnection();
bool returnValue = false;
try
{
using (SQLiteCommand sqlCommand = new SQLiteCommand("select count(FileName) from downloadedfiles where fileName = '#Filename'", sql_con))
{
sql_con.Open();
sqlCommand.Parameters.Add(new SQLiteParameter("#FileName", fileName));
long userCount = (long)sqlCommand.ExecuteScalar();
if (userCount > 0)
{
returnValue = true;
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return returnValue;
}
Two things,
first point - Originally I had my userCount as int, but it kept saying cast error... why would it have been doing that?
Second point - userCount always returns 0, even when there is data with the same fileName in the table..
Thanks
select count(FileName)
from downloadedfiles
where fileName = '#Filename'
'#Filename'=>#Filename
1st you should not use quotes in parameter. 2nd you name the parameter #Filename in your query where as you use #FileName when you add it. Those 2 have as result your query to always return null. Try:
using (SQLiteCommand sqlCommand = new SQLiteCommand("select count(FileName) from downloadedfiles where fileName = #Filename", sql_con))
{
sql_con.Open();
sqlCommand.Parameters.Add(new SQLiteParameter("#Filename", fileName));
int userCount = (int)sqlCommand.ExecuteScalar();
if (userCount > 0)
{
returnValue = true;
}
}

If there is no row in database sum command return an error

An error is thrown when there is no data in data base while converting a string value into int.
try {
SqlCommand cmdc = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=1 AND Crdt_typ_id=1", con);
string companya_credit_amount = null, comapnyb_credit_amount = null;
con.Open();
SqlDataReader drc = cmdc.ExecuteReader();
if (drc.HasRows)
{
while (drc.Read())
{
companya_credit_amount = drc[0].ToString();
}
drc.Close();
con.Close();
}
SqlCommand cmdcp = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=2 AND Crdt_typ_id=1", con);
con.Open();
SqlDataReader drcp = cmdcp.ExecuteReader();
if (drcp.HasRows)
{
while (drcp.Read())
{
companyb_credit_amount = drcp[0].ToString();
}
drcp.Close();
con.Close();
}
if (!Page.IsPostBack)
{
int companyA = 0,companyB=0;
if (companya_credit_amount != "") { companyA = Convert.ToInt32(credit_amount.ToString()); }
if (companyb_credit_amount != ""){ companyB = Convert.ToInt32(companyb_credit_amount); }
int total = (companyA+companyB);
count_total_lbl.Text = "Rs." + " " + total.ToString();
count_comapnya_lbl.Text = "Rs." + " " + companya_credit_amount.ToString();
count_companyb_lbl.Text ="Rs."+" "+ companyb_credit_amount.ToString();
}
}
catch(Exception ex) { Label2.Text = ex.ToString(); }
If there is value its working fine.but when there is no value in data base there is an error msg.
System.FormatException: Input string was not in a correct format.
Use IsDBNull to check for null values
Create and destroy all your type instances that implement IDisposable in using blocks. This ensures that connections are always released and resources are cleaned up.
Do not use connections across a class. Create them when needed and then dispose of them. Sql Server will handle connection pooling.
Get the native types directly, not the string equivalent! See changes to GetInt32 instead of ToString on the data reader.
You should refactor this to use SqlParameter's and make the retrieval statement generic OR get both SUM values in 1 sql call.
There is an if (!Page.IsPostBack) statement, if none of this code does anything if it is a postback then check at the top of the page and do not execute the sql statements if it is a postback. Otherwise the code is making (possibly) expensive sql calls for no reason.
try
{
int companyA = 0,companyB=0;
using(var con = new SqlConnection("connectionStringHere"))
{
con.Open();
using(SqlCommand cmdc = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=1 AND Crdt_typ_id=1", con))
using(SqlDataReader drc = cmdc.ExecuteReader())
{
if (drc.Read() && !drc.IsDBNull(0))
companyA = drc.GetInt32(0);
}
using(SqlCommand cmdcp = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=2 AND Crdt_typ_id=1", con))
using(SqlDataReader drcp = cmdcp.ExecuteReader())
{
if (drcp.Read() && !drcp.IsDBNull(0))
companyB = drcp.GetIn32(0);
}
}
// if you are not going to do anything with these values if its not a post back move the check to the top of the method
// and then do not execute anything if it is a postback
// ie: // if (Page.IsPostBack) return;
if (!Page.IsPostBack)
{
int total = (companyA+companyB);
count_total_lbl.Text = "Rs." + " " + total.ToString();
count_comapnya_lbl.Text = "Rs." + " " + companyA.ToString();
count_companyb_lbl.Text ="Rs."+" "+ companyB.ToString();
}
}
catch(Exception ex) { Label2.Text = ex.ToString(); }
Try to replace this
SELECT SUM(Credited_amount)
WITH
SELECT ISNULL(SUM(Credited_amount),0)
Also find one confusing code while converting Credited amount values
if (companya_credit_amount != "") { companyA = Convert.ToInt32(credit_amount.ToString()); }
---------^^^^^
if (companyb_credit_amount != ""){ companyB = Convert.ToInt32(companyb_credit_amount); }
I don't know about your business requirement but What i think Instead of using credit_amount value companya_credit_amount should be use to show value for companyA variable right?
You should do 2 things:
string companya_credit_amount = "", comapnyb_credit_amount = "";
Before assigning the value to these string variable you should check for db null as following:
while (drc.Read())
{
companya_credit_amount = (drc[0] != DbNull.Value) ? drc[0].ToString() : "" ;
}
Similarely
while (drcp.Read())
{
companyb_credit_amount = (drcp[0] != DbNull.Value) ? drcp[0].ToString() : "";
}
Try it.
You need to initialize credit_amount to empty and check if db value is null as shown below:
try {
companya_credit_amount = string.Empty;
companyb_credit_amount = string.Empty;
SqlCommand cmdc = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=1 AND Crdt_typ_id=1", con);
string companya_credit_amount = null, comapnyb_credit_amount = null;
con.Open();
SqlDataReader drc = cmd
c.ExecuteReader();
if (drc.HasRows)
{
while (drc.Read())
{
companya_credit_amount = drcp.IsDBNull(0)?string.Empty:Convert.ToString(drcp[0]);
}
drc.Close();
con.Close();
}
SqlCommand cmdcp = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=2 AND Crdt_typ_id=1", con);
con.Open();
SqlDataReader drcp = cmdcp.ExecuteReader();
if (drcp.HasRows)
{
while (drcp.Read())
{
companyb_credit_amount = drcp.IsDBNull(0)?string.Empty:Convert.ToString(drcp[0]);
}
drcp.Close();
con.Close();
}
if (!Page.IsPostBack)
{
int companyA = 0,companyB=0;
if (companya_credit_amount != "") { companyA = Convert.ToInt32(credit_amount.ToString()); }
if (companyb_credit_amount != ""){ companyB = Convert.ToInt32(companyb_credit_amount); }
int total = (companyA+companyB);
count_total_lbl.Text = "Rs." + " " + total.ToString();
count_comapnya_lbl.Text = "Rs." + " " + companya_credit_amount.ToString();
count_companyb_lbl.Text ="Rs."+" "+ companyb_credit_amount.ToString();
}
}
catch(Exception ex) { Label2.Text = ex.ToString(); }

Method Returning only " "

I need return string of DateTime. More this method is returning only null
receives an input string, convert to DateTime and i need put DateTime on valor.retorna_date_time string variable.
Code:
public void Search_DATE(string param_date)
{
SqlDataReader objReader;
SqlCommand objcmd = null;
vsql = "SELECT [IDCADASTRO],[RGP],[PEIXE],[PESO],[QUANTIDADE],[DATA_REGISTRO] FROM cadastro WHERE DATA_REGISTRO LIKE #DATA_REGISTRO";
if (this.Conectar())
{
try
{
DateTime dtParam = DateTime.Parse(param_date);
objcmd = new SqlCommand(vsql, objCon);
objcmd.Parameters.Add(new SqlParameter("#DATA_REGISTRO", dtParam));
objReader = objcmd.ExecuteReader();
if (objReader.Read())
{
valor.retorna_date_time = objReader.GetString(6);
}
}
catch (SqlException erro)
{
throw erro;
}
finally
{
this.Desconectar();
}
}
}
Input Parameters:
DateTime myDateTime = DateTime.Now;
string DateTimesql = myDateTime.ToString("dd-MM-yyyy");
objSQL.Search_DATE(DateTimesql);
valor.retorna_date_time is a global string variable.
Your SELECT statement returns 6 columns:
[IDCADASTRO],[RGP],[PEIXE],[PESO],[QUANTIDADE],[DATA_REGISTRO]
But IDatareader's GetString(n) method is 0-based, so GetString(6) returns the 7th column, which there isn't.
Change it to GetString(5).
Without seeing your table structure, I would try GetOrdinal.
Change
valor.retorna_date_time = objReader.GetString(6)
to
valor.retorna_date_time = objReader.GetOrdinal("DATA_REGISTRO");
Since you only seem to need just the last column, you can change your query to:
"SELECT [DATA_REGISTRO] FROM cadastro WHERE DATA_REGISTRO LIKE #DATA_REGISTRO";
And then read it using ExecuteScalar
objcmd = new SqlCommand(vsql, objCon);
objcmd.Parameters.AddWithValue("#DATA_REGISTRO", dtParam);
valor.retorna_date_time = objcmd.ExecuteScalar().ToString();
EDIT:
ExecuteScalar() will return a null reference if the query did not return anything.
You should check if it is null before converting it to string and passing it to valor.retorna_date_time. Do something like:
string returnValue = objcmd.ExecuteScalar() == null ?? String.Empty : objcmd.ExecuteScalar().ToString();

Why am I getting, "A column ID occurred more than once in the specification"?

I've got code that creates a table if it doesn't exist and adds all necessary columns, but for cases where the user has an older version of the table, it adds some new
columns. Yet when that second condition is true and the DDL to add columns runs, I get, "A column ID occurred more than once in the specification"
Here is the code, along with the helper functions to determine existence of table and column:
bool tableExists = dbconn.isValidTable(tablename) != -1;
if (!tableExists)
{
ddl = "CREATE TABLE Bla (. . . salvationID nvarchar(19), salvation float, discount float)";
dbconn.DBCommand(ddl, false);
}
else // (the table does exist)
{
if(!dbconn.isValidField(tablename,"redemptionID"))
{
ddl = string.Format("ALTER TABLE {0} ADD redemptionID nvarchar(19) ", tablename);
dbconn.DBCommand(ddl,false);
. . .
public int isValidTable(string tableName)
{
int validTable = -1;
string tblQuery = string.Format("SELECT COUNT(*) FROM {0}", tableName);
checkConnection();
try
{
SqlCeCommand cmd = objCon.CreateCommand();
cmd.CommandText = tblQuery;
object objcnt = cmd.ExecuteScalar();
validTable = Int32.Parse(objcnt.ToString());
}
catch
{
validTable = -1;
}
return validTable;
}
//This has been beautified/elegantized thanks to p.s.w.g at http://stackoverflow.com/questions/15693639/how-can-i-determine-whether-a-column-exists-in-a-sql-server-ce-table-with-c
public bool isValidField(string tableName, string columnName)
{
bool retVal;
string tblQuery = "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = #tableName AND
COLUMN_NAME = #columnName";
checkConnection();
try
{
SqlCeCommand cmd = objCon.CreateCommand();
cmd.CommandText = tblQuery;
SqlCeParameter tblNameParam = new SqlCeParameter("#tableName", SqlDbType.NVarChar, 128);
tblNameParam.Value = tableName;
cmd.Parameters.Add(tblNameParam);
SqlCeParameter colNameParam = new SqlCeParameter("#columnName", SqlDbType.NVarChar, 128);
colNameParam.Value = tableName;
cmd.Parameters.Add(colNameParam);
object objvalid = cmd.ExecuteScalar();
retVal = !Convert.IsDBNull(objvalid);
}
catch
{
retVal = false;
}
return retVal;
}
I suspect what's going on is that isValidField() is throwing an exception and your catch is simply swallowing it while stating the field doesn't exist... when it probably does.
I would highly suggest that instead of just swallowing it that you actually display the message so that you know what's going on.
For example:
public bool isValidField(string tableName, string columnName)
{
bool retVal;
string tblQuery = "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = #tableName AND COLUMN_NAME = #columnName";
checkConnection();
try
{
SqlCeCommand cmd = objCon.CreateCommand();
cmd.CommandText = tblQuery;
SqlCeParameter tblNameParam = new SqlCeParameter("#tableName", SqlDbType.NVarChar, 128);
tblNameParam.Value = tableName;
cmd.Parameters.Add(tblNameParam);
SqlCeParameter colNameParam = new SqlCeParameter("#columnName", SqlDbType.NVarChar, 128);
colNameParam.Value = tableName;
cmd.Parameters.Add(colNameParam);
object objvalid = cmd.ExecuteScalar();
retVal = !Convert.IsDBNull(objvalid);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
retVal = false; // <-- wrong answer
}
return retVal;
}
Also, that function should not be a boolean. You have 3 conditions: 1. It exists; 2. It doesn't exist; 3. error occurred.
In the event of an error you don't want the later methods to think that it couldn't find it. Also, I'd do the same thing to where you are validating the table exists.
Try checking for DBNull.Value.
try
{
SqlCeCommand cmd = objCon.CreateCommand();
cmd.CommandText = tblQuery;
object objcnt = cmd.ExecuteScalar();
if ((objcnt != null) && (objcnt != DBNull.Value)) {
validTable = Int32.Parse(objcnt.ToString());
} else {
MessageBox.Show("NULL returned from CreateCommand. Remove this line.");
}
}
catch

Can't insert a record in a oracle database using C#

try
{
int val4 = Convert.ToInt32(tbGrupa.Text);
string MyConString = "Data Source=**;User ID=******;Password=*****";
OracleConnection conexiune = new OracleConnection(MyConString);
OracleCommand comanda = new OracleCommand();
comanda.Connection = conexiune;
conexiune.Open();
comanda.Transaction = conexiune.BeginTransaction();
int id_stud = Convert.ToInt16(tbCodStud.Text);
string nume = tbNume.Text;
string prenume = tbPrenume.Text;
string initiala_tatalui = tbInitiala.Text;
string email = tbEmail.Text;
string facultate = tbFac.Text;
int grupa = Convert.ToInt16(tbGrupa.Text);
string serie = tbSeria.Text;
string forma_de_inv = tbFormaInvatamant.Text;
DateTime data_acceptare_coordonare = dateTimePicker1.Value;
DateTime data_sustinere_licenta = dateTimePicker2.Value;
string sustinere = tbSustinereLicenta.Text;
string parola_acces = tbParola.Text;
try
{
comanda.Parameters.AddWithValue("id_stud", id_stud);
comanda.Parameters.AddWithValue("nume", nume);
comanda.Parameters.AddWithValue("prenume", prenume);
comanda.Parameters.AddWithValue("initiala_tatalui", initiala_tatalui);
comanda.Parameters.AddWithValue("facultate", facultate);
comanda.Parameters.AddWithValue("email", email);
comanda.Parameters.AddWithValue("seria", serie);
comanda.Parameters.AddWithValue("grupa", grupa);
comanda.Parameters.AddWithValue("forma_de_inv", forma_de_inv);
comanda.Parameters.AddWithValue("data_acceptare_coordonare", data_acceptare_coordonare);
comanda.Parameters.AddWithValue("data_sustinere_licenta", data_sustinere_licenta);
comanda.Parameters.AddWithValue("sustinere_licenta", sustinere);
comanda.Parameters.AddWithValue("parola_acces", parola_acces);
comanda.Transaction.Commit();
MessageBox.Show("Studentul " + tbNume.Text + " " + tbPrenume.Text + " a fost adăugat în baza de date!");
}
catch (Exception er)
{
comanda.Transaction.Rollback();
MessageBox.Show("ER1.1:" + er.Message);
MessageBox.Show("ER1.2:" + er.StackTrace);
}
finally
{
conexiune.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("ER2.1:"+ex.Message);
MessageBox.Show("ER2.2:"+ex.StackTrace);
}
There doesn't seem to be an insert statement. I think this is what the problem is. You would need some thing like:
using (OracleConnection connection = new OracleConnection(connectionString))
{
OracleCommand command = new OracleCommand(myExecuteQuery, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
There's a commit statement, what what are you going to commit if there's no insert statement prior to that?

Categories

Resources