I'm stumped, I have been trying to execute this and nothing happens. I know that the code reaches this point but it doesn't matter if I put gibberish in the SQL statement, it doesn't throw an error.
protected string checkLaptopStatus(String cardID)
{
String ConnString = GetConnectSQLServer();
String currentStatus = "";
int i = 0;
using (SqlConnection m_dbConnection = new SqlConnection(ConnString))
{
String sql = "SELECT laptopStatus FROM tblDevices WHERE cardID = " + cardID + "'";
m_dbConnection.Open();
// CODE REACHES THIS POINT BUT NEVER PASSES THIS ?
using (SqlCommand cmd = new SqlCommand(sql, m_dbConnection))
{
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
currentStatus = Convert.ToString(dr["laptopStatus"]);
i++;
}
}
}
}
return currentStatus;
}
Changed the code as advised and used the exception error message to find out what went wrong. thanks Joel for being kind and helping.
protected void SQLReaderLaptops(string cardID)
{
String ConnString = GetConnectSQLServer();
int i = 0;
String todaysDate = DateTime.Now.ToString("yyyy'-'MM'-'dd");
String laptopID = "";
try {
using (SqlConnection m_dbConnection = new SqlConnection(ConnString))
{
String sql = "Select laptopID From tblDevices WHERE cardID= #cardID";
m_dbConnection.Open();
using (SqlCommand cmd = new SqlCommand(sql, m_dbConnection))
{
cmd.Parameters.AddWithValue("#cardID", cardID);
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
laptopID = Convert.ToString(dr["laptopID"]);
i++;
}
}
}
}
}
catch(Exception ex)
{
//CAUGHT THE ISSUE HERE AND FOUND IT WAS A BAD COLUMN NAME
}
Related
I have a code that I use to login.
I call the data I get from textbox with a method and check the records with select query in the
database.
I call to relevant method , when I press the button.
private void btnGiris_Click(object sender, EventArgs e)
{
LoginBilgiler lb = new LoginBilgiler();
bool sonuc = lb.GirisKontrol(txtAd.Text, txtSifre.Text);
}
But I encounter errors in cmd.ExecuteReader the below.
public bool GirisKontrol(string ad,string sifre)
{
using (OracleConnection con = new OracleConnection(connectionString))
{
string query = String.Format("SELECT count(*) from Z_LABEL_USER where USERNAME=({0}) and PASSWORD=({1})", ad,sifre);
OracleCommand cmd = new OracleCommand(query, con);
con.Open();
OracleDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
kAdi = ad;
con.Close();
return true;
}
else
con.Close();
return false;
}
}
The table I use for the select query.
Oracle.ManagedDataAccess.Client.OracleException: 'ORA-01722: invalid
number'
Please, don't hardcode parameters in SQL; parametrize it instead:
public bool GirisKontrol(string ad, string sifre) {
//DONE: validate public methods' input
if (string.IsNullOrEmpty(ad))
return false; // or throw exception
else if (string.IsNullOrEmpty(sifre))
return false; // or throw exception
using (OracleConnection con = new OracleConnection(connectionString)) {
con.Open();
//DONE: no need to count all the entires, just check if there's at least one
//DONE: keep query readable
//DONE: paramterize queries
string query =
#"select 1
from Z_LABEL_USER
where USERNAME = :prm_UserName
and PASSWORD = :prm_Password";
using (OracleCommand cmd = new OracleCommand(query, con)) {
//TODO: this syntax can vary from library to library you use to work with Oracle
cmd.Parameters.Add(":prm_UserName", OracleType.VarChar).Value = ad;
cmd.Parameters.Add(":prm_Password", OracleType.VarChar).Value = sifre;
using (OracleDataReader dr = cmd.ExecuteReader()) {
if (dr.Read()) {
//TODO: Side effect : it changes instance's state. Do you really want it?
kAdi = ad;
return true;
}
}
}
}
return false;
}
I am previously only familiar with Linq and the like for data access. I am working on something now that requires me to use actual SQL commands on the back end to return a single value. My code compiles and runs, however it is returning null for a value that I know should be returning something besides an empty string...
Is my structure off on this? Or is something else missing?
Below is my code:
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
using (SqlConnection conn = new SqlConnection(connString))
{
string sql = "SELECT Description FROM person_gender_lookup WHERE ID = #sex";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
newSex = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
Here is a picture of the result set of the table:
Open the connection.
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open(); //<- This line here.
string sql = "SELECT Description FROM person_gender_lookup WHERE ID = #sex";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
newSex = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
cmd.ExecuteScalar() is probably throwing an InvalidOperationException because you haven't opened the connection. The exception is being caught, outputted to the console, then the initial value of newSex is begin returned since the call to ExecuteScalar threw.
ID is a int or varchar?
If is int use:
cmd.Parameters.Add("#sex", SqlDbType.Int).Value = sex;
instead of:
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
P.S.
Query parameters and parameter add into cmd.Parameters is case sensitive.
Write
#sex
instead of
#Sex
Figured it out. Had to open the cmd and close it AFTER I set the newSex variable to the value being pulled.
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
DataSet ds = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
using (SqlConnection conn = new SqlConnection(connString))
{
string sql = "SELECT Description FROM person_gender_lookup WHERE ID = #Sex";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
cmd.Connection = conn;
adapter.SelectCommand = cmd;
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
adapter.Fill(ds);
newSex = cmd.ExecuteScalar().ToString();
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
}
Try this:
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
using (SqlConnection conn = new SqlConnection(connString))
{
string sql = "SELECT Description FROM person_gender_lookup WHERE ID" + sex;;
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
newSex = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
I am having the below code where I am querying the MySQL database. I need to replace my select query to prepare statement
public static void ValidateName(List<Employees> EmpList, string Grp)
{
var connStr = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
string selectQuery;
for (int i = 0; i < EmpList.Count; i++)
{
selectQuery = "Select EmpName from Employee where group = #Grp AND #Name in (FirstName, LastName);";
using (MySqlConnection conn = new MySqlConnection(connStr))
using (MySqlCommand cmd = new MySqlCommand(selectQuery, conn))
{
cmd.Parameters.Add("#Grp", MySqlDbType.VarChar).Value = Grp;
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = EmpList[i].Name;
conn.Open();
var reader = cmd.ExecuteReader();
List<string> lineList = new List<string>();
while (reader.Read())
{
lineList.Add(reader.GetString(0));
}
if (lineList.Count <=0)
{
WriteValidationFailure(EmpList[i], "Name doesnot exists in the DB");
}
conn.Close();
}
}
}
This code works perfectly. But for improvement I need to use the prepare statements instead of the query I am using. Because I am having similar kinds of various validation in my code, I am not sure how to reuse the parameters effectively.
You are very close. Just call cmd.Prepare(), keep references to the parameters, and reuse the command:
public static void ValidateName(List<Employees> EmpList, string Grp)
{
var connStr = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
string selectQuery;
selectQuery = "Select EmpName from Employee where group = #Grp AND #Name in (FirstName, LastName);";
using (MySqlConnection conn = new MySqlConnection(connStr)) {
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(selectQuery, conn))
{
var prmGrp = cmd.Parameters.Add("#Grp", MySqlDbType.VarChar);
var prmName = cmd.Parameters.Add("#Name", MySqlDbType.VarChar);
cmd.Prepare();
for (int i = 0; i < EmpList.Count; i++)
{
prmGrp.Value = Grp;
prmName.Value = EmpList[i].Name;
using (var reader = cmd.ExecuteReader()) {
List<string> lineList = new List<string>();
while (reader.Read())
{
lineList.Add(reader.GetString(0));
}
if (lineList.Count <=0)
{
WriteValidationFailure(EmpList[i], "Name doesnot exists in the DB");
}
}
}
}
conn.Close();
}
}
I Have a question regarding SQL commands. I could not seems to get the while loop running under the "while(dr.read())". Below Are my sample code in C# Windows Form.
Thank You.
cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM network";
MySqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
string datasource = dr[1].ToString();
string datadestination = dr[2].ToString();
if (source == datasource && destination == datadestination)
{
int newcounter;
newcounter = Convert.ToInt32(dr[4]) + 1;
cmd.CommandText = "UPDATE network set counter = #nnnewcounter";
cmd.Parameters.AddWithValue("#nnnewcounter", newcounter);
}
else
{
cmd.CommandText = "INSERT INTO network(source,destination,length,counter) VALUES (#sssource,#dddestination,#lllength,#cccounter)";
cmd.Parameters.AddWithValue("#sssource", source);
cmd.Parameters.AddWithValue("#dddestination", destination);
cmd.Parameters.AddWithValue("#lllength", length);
cmd.Parameters.AddWithValue("#cccounter", 1);
}
}
You have a few issues with this first you’re reusing the same command and using different parameters at which point you should clear them. It is also not clear if your are Opening the connection for the datareader. I would therefore move the insert and update outside the SQLDataReader as it would make the code easier to read.
using (SqlConnection connection = new SqlConnection(ConnString))
{
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = "SELECT * FROM network";
cmd.Connection.Open();
using (MySqlDataReader dr = cmd.ExecuteReader())
{
if (dr .HasRows)
{
while (dr.Read())
{
string datasource = dr[1].ToString();
string datadestination = dr[2].ToString();
if (source == datasource && destination == datadestination)
{
int newcounter;
newcounter = Convert.ToInt32(dr[4]) + 1;
Updateddos_network(newcounter);
}
else
{
Savedoss_network(source,destination, length, 1);
}
}
else
{
//No rows found
}
}
}
}
Then outside the method in the same class you could have.
private void Updateddos_network(int newcounter)
{
using (SqlConnection connection = new SqlConnection(ConnString))
{
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = "UPDATE ddos_network set counter = #nnnewcounter";
cmd.Parameters.AddWithValue("#nnnewcounter", newcounter);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
}
private void Insertddos_network(string source, string destination, int length, int counter)
{
using (SqlConnection connection = new SqlConnection(ConnString))
{
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = "INSERT INTO ddos_network(source,destination,length,counter) VALUES (#sssource,#dddestination,#lllength,#cccounter)";
cmd.Parameters.AddWithValue("#sssource", source);
cmd.Parameters.AddWithValue("#dddestination", destination);
cmd.Parameters.AddWithValue("#lllength", length);
cmd.Parameters.AddWithValue("#cccounter", counter);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
}
If you were to refactor your code further you could have a Save method for your ddos_network object which could then be used to demine if your object is being updated or inserted based upon if the current object has an Id for example.
I've been searching for hours now. I can't find anything helpful for my problem.
The Read()-function always returns false. If I run the SQL-command with sqlplus I get this result:
GERA_ID GETY_BEZEICHNUNG
---------------------------
100001 Blackberry
100002 GSM
here's a simplified version of the code:
List<Divice> divices = new List<Divice>();
using (OracleConnection connection = new OracleConnection(connectionString))
{
OracleCommand cmd = new OracleCommand("select gera_id, gety_bezeichnung from idc_geraet, idc_geraettyp where idc_geraettyp.gety_id = idc_geraet.gety_id and pers_id = 4711");
cmd.Connection = connection;
connection.Open();
OracleDataReader reader = cmd.ExecuteReader();
while(reader.Read()) //returns always false
{
Divice g = new Divice();
g.gera_id = reader.GetDecimal(0);
g.gety_bezeichnung = reader.GetString(1);
divices.Add(g);
}
reader.Close();
}
EDIT:
This Code is called before. and it works fine:
IDC_PERSON p = new IDC_PERSON();
using (OracleConnection connection = new OracleConnection(connectionString))
{
OracleCommand cmd = new OracleCommand("select PERS_VNAME, PERS_NNAME, PERS_EINTRDATUM from idc_person where PERS_ID = 4711");
cmd.Connection = connection;
connection.Open();
OracleDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (reader.Read())
{
p.PERS_ID = user_id;
p.PERS_VNAME = reader.GetString(0);
p.PERS_NNAME = reader.GetString(1);
p.PERS_EINTRDATUM = reader.GetDateTime(2);
}
reader.Close();
}
So, here is the whole code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Oracle.DataAccess.Client;
using TelKoOpt.Models;
using System.Data;
namespace TelKoOpt.Controllers
{
public class HomeController : Controller
{
string connectionString = "user id=scott;password=tiger;" +
"data source=(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)" +
"(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl)))";
public ActionResult Index(int user_id)
{
MyDbContext dbcontext = new MyDbContext();
IDC_PERSON p = new IDC_PERSON();
List<IDC_GERAET> geraete = new List<IDC_GERAET>();
List<TELGSMEGN> telgsmegn = new List<TELGSMEGN>();
dbcontext.pers = p;
dbcontext.geraete = geraete;
dbcontext.telgsmegn = telgsmegn;
using (OracleConnection connection = new OracleConnection(connectionString))
{
OracleCommand cmd = new OracleCommand("select PERS_VNAME, PERS_NNAME, PERS_EINTRDATUM from idc_person where PERS_ID = " + user_id);
//OracleCommand cmdTelg = new OracleCommand("select service, sum(betrag), sum(dauer), sum(anzahl), zonen from test_telgsmegn where gera_id = " + user_id + " and datumaktion between '" + "01.02.2012" + "' and '" + "20.03.2012" + "' group by service, zonen; ");
cmd.Connection = connection;
//cmdTelg.Connection = new OracleConnection(connectionString);
try
{
connection.Open();
OracleDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
p.PERS_ID = user_id;
p.PERS_VNAME = reader.GetString(0);
p.PERS_NNAME = reader.GetString(1);
p.PERS_EINTRDATUM = reader.GetDateTime(2);
}
reader.Close();
}
catch (OracleException)
{
//return View(dbcontext);
}
}
using (OracleConnection connection = new OracleConnection(connectionString))
{
OracleCommand cmd = new OracleCommand("select gera_id, gety_bezeichnung from idc_geraet, idc_geraettyp where idc_geraettyp.gety_id = idc_geraet.gety_id and pers_id = " + user_id);
cmd.Connection = connection;
try
{
connection.Open();
OracleDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
IDC_GERAET g = new IDC_GERAET();
g.gera_id = reader.GetDecimal(0);
g.gety_bezeichnung = reader.GetString(1);
geraete.Add(g);
}
reader.Close();
}
catch (OracleException)
{
//return View(dbcontext);
}
}
return View(dbcontext);
}
}
}
This may not be the answer for your case, but I ran into a similar issue when debugging code and it may help others who come across this question.
The solution I figured out was actually only specific to when you are debugging. When stepping through code, if you expand the "Results View" (which enumerates the enumerable), when you get to the part in your code that reads the data reader, the reader will already be at the end of the results, and will return false. This is because data readers are forward only, and once you've enumerated to the next result (which was done by the debugger in this case), you can't go back.
same issue faced by me this is how i fixed
use out type
public void ExecuteStoredProcReturnDataReader(string sQueryName, out IDataReader dr, List<DBParam> oParams =null)
{
try
{
dbHelper DBProvider = new dbHelper();
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
oCmd = DBProvider.CreateCommand(sQueryName, conn);
if (oParams !=null)
DBProvider.CreateParameters(oParams, ref oCmd);
dr = oCmd.ExecuteReader();
}
catch (Exception e)
{
rethrow = DataAccessExceptionHandler.HandleException(ref e);
if (rethrow)
{
throw e;
}
dr = null;
}
}