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
}
I'm first time for C#, Now I try to insert data to oracle db from variable. But I got this error. I don't know what point in this source code .
public class Foo
{
public string PLANTCODE { get; set; }
public string LOCATIONCODE { get; set; }
public string LOCATIONNAME { get; set; }
public string LOCATIONSTATUS { get; set; }
public string DEPARTMENTCODE { get; set; }
public string DEPARTMENTNAME { get; set; }
// public DateTime LASTUPDATED { get; set; }
// public OracleDbType OracleDbType { get; set; }
}
public List<Foo> GetData()
{
List<Foo> dataList = new List<Foo>();
string connectionString = "Data Source=xxx; Initial Catalog=xxx;Integrated Security = false; User ID=xxx;Password=xxx";
string selectStatement = "SELECT PLANTCODE,LOCATIONCODE,LOCATIONNAME,LOCATIONSTATUS,DEPARTMENTCODE,DEPARTMENTNAME from V_Location";
using (var con = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand(selectStatement, con))
{
con.Open();
using (var reader = cmd.ExecuteReader())
{ if (reader.Read())
{
dataList.Add(new Foo
{
PLANTCODE = reader.GetString(0),
LOCATIONCODE = reader.GetString(1),
LOCATIONNAME = reader.GetString(2),
LOCATIONSTATUS = reader.GetString(3),
DEPARTMENTCODE = reader.GetString(4),
DEPARTMENTNAME = reader.GetString(5),
});
}
}
}
}
return dataList;
}
public void InsertData()
{
string connectionString = "Provider=MSDAORA;Data Source=ORCL;Persist Security Info=True;User ID=xxx;Password=xxx;Unicode=True";
string insertStatment = "INSERT INTO xxx.BTH_V_LOCATION (PLANTCODE, LOCATIONCODE, LOCATIONNAME, LOCATIONSTATUS, DEPARTMENTCODE, DEPARTMENTNAME) VALUES (:PLANTCODE, :LOCATIONCODE, :LOCATIONNAME, :LOCATIONSTATUS, :DEPARTMENTCODE, :DEPARTMENTNAME)";
List<Foo> dataList = GetData();
if (dataList.Count > 0)
{
using (OleDbConnection con = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand(insertStatment, con))
{
con.Open();
foreach (var items in dataList)
{
cmd.Parameters.Clear();
cmd.Parameters.Add("PLANTCODE", OleDbType.VarChar).Value = items.PLANTCODE;
cmd.Parameters.Add("LOCATIONCODE", OleDbType.VarChar).Value = items.LOCATIONCODE;
cmd.Parameters.Add("LOCATIONNAME", OleDbType.VarChar).Value = items.LOCATIONNAME;
cmd.Parameters.Add("LOCATIONSTATUS", OleDbType.VarChar).Value = items.LOCATIONSTATUS;
cmd.Parameters.Add("DEPARTMENTCODE", OleDbType.VarChar).Value = items.DEPARTMENTCODE;
cmd.Parameters.Add("DEPARTMENTNAME", OleDbType.VarChar).Value = items.DEPARTMENTNAME;
}
cmd.ExecuteNonQuery();
}
}
}
}
private void button1_Click_1(object sender, EventArgs e)
{
InsertData();
}
}
}
This source code get select data from sql server first. After that keep data in variable for insert to oracle. Now I try to insert without variable then can insert data. but if I change to insert by variable but can't insert and get this error
ORA-01008: not all variables bound error" on "cmd.ExecuteNonQuery();
Move cmd.Parameters.clear(); outside the loop.
Seems to be clearing every time.
Thank you so much for your answer, But I try to move cmd.Parameters.clear(); , I still got same error.
using (OleDbConnection con = new OleDbConnection(connectionString)) //OleDbConnection
{
using (OleDbCommand cmd = new OleDbCommand(insertStatment, con)) //OleDbCommand
{
con.Open();
foreach (var items in dataList)
{
cmd.Parameters.Add("PLANTCODE", OleDbType.VarChar).Value = items.PLANTCODE;
cmd.Parameters.Add("LOCATIONCODE", OleDbType.VarChar).Value = items.LOCATIONCODE;
cmd.Parameters.Add("LOCATIONNAME", OleDbType.VarChar).Value = items.LOCATIONNAME;
cmd.Parameters.Add("LOCATIONSTATUS", OleDbType.VarChar).Value = items.LOCATIONSTATUS;
cmd.Parameters.Add("DEPARTMENTCODE", OleDbType.VarChar).Value = items.DEPARTMENTCODE;
cmd.Parameters.Add("DEPARTMENTNAME", OleDbType.VarChar).Value = items.DEPARTMENTNAME;
}
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
}
and I try to swap "cmd.ExecuteNonQuery();" and "cmd.Parameters.Clear();" but same result.
Now I can fixed this problem, I change paramater name to "?"
string insertStatment = "INSERT INTO xxx.BTH_V_LOCATION (PLANTCODE, LOCATIONCODE, LOCATIONNAME, LOCATIONSTATUS, DEPARTMENTCODE, DEPARTMENTNAME) VALUES (?,?,?,?,?,?)";
List<Foo> dataList = GetData();
if (dataList.Count > 0)
{
using (OleDbConnection con2 = new OleDbConnection(connectionString)) //OleDbConnection
{
using (OleDbCommand cmd2 = new OleDbCommand(insertStatment, con2)) //OleDbCommand
{
con2.Open();
cmd2.Parameters.Clear();
foreach (var items in dataList)
{
cmd2.Parameters.Add("?", OleDbType.VarChar).Value = items.PLANTCODE;
cmd2.Parameters.Add("?", OleDbType.VarChar).Value = items.LOCATIONCODE;
cmd2.Parameters.Add("?", OleDbType.VarChar).Value = items.LOCATIONNAME;
cmd2.Parameters.Add("?", OleDbType.VarChar).Value = items.LOCATIONSTATUS;
cmd2.Parameters.Add("?", OleDbType.VarChar).Value = items.DEPARTMENTCODE;
cmd2.Parameters.Add("?", OleDbType.VarChar).Value = items.DEPARTMENTNAME;
//cmd2.ExecuteNonQuery();
//cmd2.Parameters.Clear();
}
cmd2.ExecuteNonQuery();
//cmd2.Parameters.Clear();
}
}
}
I think you need to use # instead of : for the parameters. And you need to execute within the loop and clear params after the execution.
string insertStatment = "INSERT INTO xxx.BTH_V_LOCATION (PLANTCODE, LOCATIONCODE, LOCATIONNAME, LOCATIONSTATUS, DEPARTMENTCODE, DEPARTMENTNAME) VALUES (#PLANTCODE, #LOCATIONCODE, #LOCATIONNAME, #LOCATIONSTATUS, #DEPARTMENTCODE, #DEPARTMENTNAME)";
List<Foo> dataList = GetData();
if (dataList.Count > 0)
{
using (OleDbConnection con = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand(insertStatment, con))
{
con.Open();
foreach (var items in dataList)
{
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#PLANTCODE", items.PLANTCODE),
new OleDbParameter("#LOCATIONCODE", items.LOCATIONCODE),
new OleDbParameter("#LOCATIONNAME", items.LOCATIONNAME),
new OleDbParameter("#LOCATIONSTATUS", items.LOCATIONSTATUS),
new OleDbParameter("#DEPARTMENTCODE", items.DEPARTMENTCODE),
new OleDbParameter("#DEPARTMENTNAME", items.DEPARTMENTNAME),
});
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
}
}
}
Invalid attempt to read when no data is present.
This error occurs on this line
string ingredientName = reader2.GetString(0);
My code:
var ingredientList = new List<Ingredient>();
SqlCommand staffCommand = new SqlCommand();
string conString = EventsUnlimited.Properties.Settings.Default.DatabaseEventsUnlimitedConnectionString;
using (SqlConnection connection = new SqlConnection(conString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("SELECT IngredientID, Quantity FROM CourseIngredients WHERE CourseID =" + courseID, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// Obtains the columns from customer
int ingredientID = reader.GetInt32(0);
decimal quantity = reader.GetDecimal(1);
string ingredientNameConstruct;
SqlCommand ingredientCommand = new SqlCommand();
string conString2 = EventsUnlimited.Properties.Settings.Default.DatabaseEventsUnlimitedConnectionString;
using (SqlConnection connection2 = new SqlConnection(conString2))
{
connection2.Open();
using (SqlCommand command2 = new SqlCommand ("SELECT IngredientName FROM Stock WHERE IngredientID =" + ingredientID, connection2))
{
using (SqlDataReader reader2 = command2.ExecuteReader())
{
string ingredientName = reader2.GetString(0);
ingredientNameConstruct = ingredientName;
}
}
}
ingredientList.Add(new Ingredient(courseID, ingredientNameConstruct, ingredientID, quantity));
}
}
}
return ingredientList;
}
I am not sure as to what is causing this issue. There is data in the table and the row I am trying to read from.
You are not calling Read() method for your reader2 object which actually reads a row against the result returned, add that before actually reading column values:
using (SqlDataReader reader2 = command2.ExecuteReader())
{
if(reader2.Read()) // this is needed
{
string ingredientName = reader2.GetString(0);
ingredientNameConstruct = ingredientName;
}
}
if you are expecting multiple rows then use while loop, and if it is always a single row to be expecting as result them you can use reader2.ExecuteScalar too as #bradbury9 mentioned in the comment:
string ingredientName = command2.ExecuteScalar()?.ToString();
ingredientNameConstruct = ingredientName;
Call DataReader.Read Method in your reader2 DataReader to get the results.
I have written the following code to extract all records from the table in the SQL server. There is no error in the code but when I run it in fiddler, I am getting null objects.
[HttpGet]
public List<Student> Get()
{
SqlDataReader reader = null;
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = #"Data Source=PALLAVI-PC\SQLEXPRESS;Initial Catalog=StudentDB;Integrated Security=True;MultipleActiveResultSets=True;";
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select * from Tbl_Students;";
sqlCmd.Connection = myConnection;
myConnection.Open();
reader = sqlCmd.ExecuteReader();
int rowCount = 0;
while (reader.Read())
{
rowCount++;
}
Student[] student = new Student[rowCount];
for(int i=0;i<rowCount;i++)
{
student[i] = new Student();
}
int j = 0;
while (reader.Read())
{
// student[j] = new Student();
student[j].Roll_Number = Convert.ToInt32(reader.GetValue(0));
student[j].FirstName = reader.GetValue(1).ToString();
student[j].LastName = reader.GetValue(2).ToString();
student[j].Class = Convert.ToInt32(reader.GetValue(3));
student[j].Gender = reader.GetValue(4).ToString();
j++;
}
return student.ToList();
myConnection.Close();
}
I have 5 records in the table. I am able to get 5 json objects but without the content.
Attaching the image from Fiddler:
Student.cs
namespace WebAPIDemo.Models
{
public class Student
{
public int Roll_Number { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Class { get; set; }
public string Gender { get; set; }
}
}
Try this, without taking count of records. I'm not using the array, I have created new instance of student for each record.
public static List<Student> GetData()
{
List<Student> lstStudent = new List<Student>();
using (SqlConnection con = new SqlConnection(#"Data Source=PALLAVI-PC\SQLEXPRESS;Initial Catalog=StudentDB;Integrated Security=True;MultipleActiveResultSets=True;"))
{
using (SqlCommand cmd = new SqlCommand("Select * from Tbl_Students;", con))
{
cmd.CommandType = CommandType.Text;
if (con.State == ConnectionState.Closed)
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
Student student =new Student();
student.Roll_Number = Convert.ToInt32(reader.GetValue(0));
student.FirstName = reader.GetValue(1).ToString();
student.LastName = reader.GetValue(2).ToString();
student.Class = Convert.ToInt32(reader.GetValue(3));
student.Gender = reader.GetValue(4).ToString();
lstStudent.Add(student);
}
}
}
return lstStudent;
}
your first while(reader.Read()) is the actual reader object with data. DataReader allows forward only read only access to a data row.The next while loop won't even execute because the Read() is already completed.So you're getting an array of 5 Student objects that are initialized with default values.
Instead of initializing an array of Student populate instances and add to a List<Student> inside the while loop.
this is how I try to print something worthwhile for my site using my class, When I try to write my class will not find it at all.
I can not find my worth to return something worthwhile for my user.
the problem is that it can not find at all class.
My class:
public class AbonnementsId
{
public int indhold { get; set; }
}
public AbonnementsId HentAbonnementsId()
{
AbonnementsId AbonnementsidReturn = new AbonnementsId();
AbonnementsidReturn.indhold = 0;
SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
SqlCommand cmd1 = conn1.CreateCommand();
cmd1.Connection = conn1;
int brugerid = Convert.ToInt32(HttpContext.Current.Session["id"]);
cmd1.CommandText = #"SELECT abonnementsid from brugere WHERE id = #id";
cmd1.Parameters.AddWithValue("#id", brugerid);
conn1.Open();
SqlDataReader readerBrugerA = cmd1.ExecuteReader();
if (readerBrugerA.Read())
{
AbonnementsidReturn.indhold = Convert.ToInt32(readerBrugerA["abonnementsid"]);
}
conn1.Close();
return AbonnementsidReturn;
}
Here is how I write my class out when I need it for my content.
if (Session["AbonnementsId"] != null)
{
_subscriptionId = long.Parse(Session["AbonnementsId"].ToString());
}
else
{
//when I need to print my class do I like it here
_subscriptionId = AbonnementsidReturn.indhold();
}
I'm totally shooting in the dark here:
public static class AbonnementsId
{
public static int GetAbonnementsId()
{
int abonnementsid;
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
using(var conn = new SqlConnection(connectionString))
{
int brugerid = Convert.ToInt32(HttpContext.Current.Session["id"]);
SqlCommand cmd1 = conn.CreateCommand();
cmd1.Connection = conn;
cmd1.CommandText = #"SELECT abonnementsid from brugere WHERE id = #id";
cmd1.Parameters.AddWithValue("#id", brugerid);
conn.Open();
SqlDataReader readerBrugerA = cmd1.ExecuteReader();
if (readerBrugerA.Read())
abonnementsid = Convert.ToInt32(readerBrugerA["abonnementsid"]);
conn.Close();
}
return abonnementsid;
}
}
You can then call this in your code:
if (Session["AbonnementsId"] != null)
{
_subscriptionId = long.Parse(Session["AbonnementsId"].ToString());
}
else
{
//when I need to print my class do I like it here
_subscriptionId = AbonnementsId.GetAbonnementsId();
}