sql statement supposed to have 2 distinct rows, but only 1 is returned - sql

I have an sql statement that is supposed to return 2 rows. the first with psychological_id = 1, and the second, psychological_id = 2. here is the sql statement
select * from psychological where patient_id = 12 and symptom = 'delire';
But with this code, with which I populate an array list with what is supposed to be 2 different rows, two rows exist, but with the same values: the second row.
OneSymptomClass oneSymp = new OneSymptomClass();
ArrayList oneSympAll = new ArrayList();
string connStrArrayList = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\PatientMonitoringDatabase.mdf; " +
"Initial Catalog=PatientMonitoringDatabase; " +
"Integrated Security=True";
string queryStrArrayList = "select * from psychological where patient_id = " + patientID.patient_id + " and symptom = '" + SymptomComboBoxes[tag].SelectedItem + "';";
using (var conn = new SqlConnection(connStrArrayList))
using (var cmd = new SqlCommand(queryStrArrayList, conn))
{
conn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
oneSymp.psychological_id = Convert.ToInt32(rdr["psychological_id"]);
oneSymp.patient_history_date_psy = (DateTime)rdr["patient_history_date_psy"];
oneSymp.strength = Convert.ToInt32(rdr["strength"]);
oneSymp.psy_start_date = (DateTime)rdr["psy_start_date"];
oneSymp.psy_end_date = (DateTime)rdr["psy_end_date"];
oneSympAll.Add(oneSymp);
}
}
conn.Close();
}
OneSymptomClass testSymp = oneSympAll[0] as OneSymptomClass;
MessageBox.Show(testSymp.psychological_id.ToString());
the message box outputs "2", while it's supposed to output "1". anyone got an idea what's going on?

You're adding the same instance to the ArrayList twice. Try this:
List<OneSymptomClass> oneSympAll = new List<OneSymptomClass>();
string connStrArrayList =
"Data Source=.\\SQLEXPRESS;" +
"AttachDbFilename=|DataDirectory|\\PatientMonitoringDatabase.mdf; " +
"Initial Catalog=PatientMonitoringDatabase; " +
"Integrated Security=True";
Patient patientID;
string queryStrArrayList =
"select * from psychological where patient_id = " +
patientID.patient_id + " and symptom = '" +
SymptomComboBoxes[tag].SelectedItem + "';";
using (var conn = new SqlConnection(connStrArrayList))
{
using (var cmd = new SqlCommand(queryStrArrayList, conn))
{
conn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
OneSymptomClass oneSymp = new OneSymptomClass();
oneSymp.psychological_id =
Convert.ToInt32(rdr["psychological_id"]);
oneSymp.patient_history_date_psy =
(DateTime) rdr["patient_history_date_psy"];
oneSymp.strength = Convert.ToInt32(rdr["strength"]);
oneSymp.psy_start_date =
(DateTime) rdr["psy_start_date"];
oneSymp.psy_end_date =
(DateTime) rdr["psy_end_date"];
oneSympAll.Add(oneSymp);
}
}
conn.Close();
}
}
MessageBox.Show(oneSympAll[0].psychological_id.ToString());
MessageBox.Show(oneSympAll[1].psychological_id.ToString());
Note that I replaced the ArrayList with a List<OneSymptomClass>. There is no reason to use ArrayList unless you're using .NET 1.1.

thx for the tip John Saunders. I added a line that makes it work. was that what you were gonna suggest me?
while (rdr.Read())
{
oneSymp = new OneSymptomClass();
oneSymp.psychological_id = Convert.ToInt32(rdr["psychological_id"]);
oneSymp.patient_history_date_psy = (DateTime)rdr["patient_history_date_psy"];
oneSymp.strength = Convert.ToInt32(rdr["strength"]);
oneSymp.psy_start_date = (DateTime)rdr["psy_start_date"];
oneSymp.psy_end_date = (DateTime)rdr["psy_end_date"];
oneSympAll.Add(oneSymp);
}

Related

How to iterate through the table and get the value of a cell? (MVC)

I have this table called "Events" with where there are columns named 'EquipID' and 'EmailSent' respectively.
The default value for 'EmailSent' is "no" when a data is inserted. Now I have to run a query to iterate through every single row whether an e-mail has been sent or not based on the value. If the query reads 'no', then I have to perform a SMTP function to send a mail according to the corresponding 'EquipID' to it, where I have to fetch the cell value of it. A row can be skipped if the query reads 'yes' instead.
Now I have no idea on how to call a table and query the iteration to get the value of the cells only if the value of 'EmailSent' is 'no'.
I have attached the table design and data together.
I did something like this so far.
con.Open();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MVCConnectionString"].ConnectionString))
{
//replace this with your query
using (var command = new SqlCommand("SELECT EventID, EquipID, EmailSent FROM Events", con))
{
con.Open();
using (var reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
if (reader["EmailSent"].ToString() == "no")
{
string IDIDID = reader["EquipID"].ToString();
//add your function to send email
string sqlView = "SELECT * FROM [NewEquipment] INNER JOIN [User] ON [NewEquipment].[UserID] = [User].[UserID] WHERE EquipID = '" + IDIDID + "'";
using (SqlCommand yes = new SqlCommand(sqlView, con))
{
SqlDataReader read = yes.ExecuteReader();
if (read.Read())
{
string UserEmail = read["UserEmailAdd"].ToString();
string UserFullName = read["UserFullName"].ToString();
string EquipIDID = read["EquipID"].ToString();
string ModelNo = read["ModelNo"].ToString();
string ModelDesc = read["ModelDesc"].ToString();
string CalType = read["CalType"].ToString();
string CalDate = read["EquipCalDueDate"].ToString();
DateTime caldate = DateTime.Parse(CalDate);
string DateDate = caldate.ToString("MM-dd-yyyy");
MailMessage mail = new MailMessage();
mail.To.Add(UserEmail);
mail.From = new MailAddress("keysight#keysight.com");
mail.Subject = "Reminder on Equipment's Cal Due Date";
mail.IsBodyHtml = true;
string Body = "Greetings " + UserFullName + "<br/><br/>This email is to remind you that you have " + "<b>10 days </b>" + "left before you can send the equipment for calibration. Below are the details of the respective equipment: " +
"<br/><br/>Equipment ID: " + EquipIDID + "<br/>Model No.: " + ModelNo + "<br/>Model Description: " + ModelDesc + "<br/>Cal Type: " + CalType + "<br/>Equipment Status: " + "<b>CRITICAL</b>" +
"<br/>Equipment Cal Due Date: " + DateDate + "<br/><br/>Thank you." + "<br/><br/>Regards," + "<br/>Keysight Technologies";
mail.Body = Body;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.cos.is.keysight.com";
smtp.Port = 25;
smtp.Send(mail);
}
read.Close();
con.Close();
}
}
}
}
}
}
}
con.Close();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MVCConnectionString"].ConnectionString))
{
//replace this with your query
using (var command = new SqlCommand("SELECT eventid,eqipid,emailsent FROM TableName", connection))
{
connection.Open();
using (var reader = command.ExecuteReader()){
if(reader.HasRows){
while(reader.Read()){
if (reader["emailsent"].ToString()=="NO"){
//add your function to send email
}
}
}
}
}
Thank you guys for your help. I found the answer for it. I've attached it below.
using (var con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\MyDatabase.mdf;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework"))
{
using (var command = con.CreateCommand())
{
command.CommandText = "SELECT EventID, EquipID, EmailSent, EquipCalDueDate, ThemeColor FROM Events";
con.Open();
using (var reader = command.ExecuteReader())
{
var indexOfColumn1 = reader.GetOrdinal("EventID");
var indexOfColumn2 = reader.GetOrdinal("EquipID");
var indexOfColumn3 = reader.GetOrdinal("EmailSent");
var indexOfColumn4 = reader.GetOrdinal("EquipCalDueDate");
var indexOfColumn5 = reader.GetOrdinal("ThemeColor");
while (reader.Read())
{
var value1 = reader.GetValue(indexOfColumn1);
var value2 = reader.GetValue(indexOfColumn2);
var value3 = reader.GetValue(indexOfColumn3);
var value4 = reader.GetValue(indexOfColumn4);
var value5 = reader.GetValue(indexOfColumn5);
if (value5.ToString() == "red" && value3.ToString() == "no") {
string sqlView = "SELECT * FROM [NewEquipment] INNER JOIN [User] ON [NewEquipment].[UserID] = [User].[UserID] WHERE EquipID = '" + value2.ToString() + "'";
using (SqlCommand yes = new SqlCommand(sqlView, con))
{
SqlDataReader read = yes.ExecuteReader();
if (read.Read())
{
string UserEmail = read["UserEmailAdd"].ToString();
string UserFullName = read["UserFullName"].ToString(); string EquipIDID = read["EquipID"].ToString();
string ModelNo = read["ModelNo"].ToString();
string ModelDesc = read["ModelDesc"].ToString();
string CalType = read["CalType"].ToString(); string CalDate = read["EquipCalDueDate"].ToString();
DateTime Edate = DateTime.Parse(CalDate);
double remainingDays = (Edate - DateTime.Now).TotalDays;
int rDays = (int)Math.Round(remainingDays, MidpointRounding.AwayFromZero);
MailMessage mail = new MailMessage();
mail.To.Add(UserEmail);
mail.From = new MailAddress("keysight#keysight.com");
mail.Subject = "Reminder on Equipment's Cal Due Date";
mail.IsBodyHtml = true;
string Body = "Greetings " + UserFullName + "<br/><br/>This email is to remind you that you have " + "<b>"+ rDays + " days </b>" + "left before you can send the equipment for calibration. Below are the details of the respective equipment: " +
"<br/><br/>Equipment ID: " + EquipIDID + "<br/>Model No.: " + ModelNo + "<br/>Model Description: " + ModelDesc + "<br/>Cal Type: " + CalType + "<br/>Equipment Status: " + "<b>CRITICAL</b>" +
"<br/>Equipment Cal Due Date: " + CalDate + "<br/><br/>Thank you." + "<br/><br/>Regards," + "<br/>Keysight Technologies";
mail.Body = Body;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.cos.is.keysight.com";
smtp.Port = 25;
smtp.Send(mail);
}
read.Close();
string yyy = "SELECT * FROM [Events] WHERE EquipID='" + value2.ToString() + "'";
using (SqlCommand cmdcmd = new SqlCommand(yyy, con))
{
SqlDataReader readread = cmdcmd.ExecuteReader();
if (readread.Read())
{
string sql = "UPDATE Events SET EmailSent='yes' WHERE EquipID = '" + value2.ToString() + "'";
SqlCommand cmd1 = new SqlCommand(sql, con);
cmd1.ExecuteNonQuery();
}
readread.Close();
}
}
}
}
}
con.Close();
}
}

ORA-00933: oracle 8i

I want to use join in Oracle 8i. I have my query as below.
I have this query of getting data from two tables using an join, but I get the error SQL command not properly ended.
private List<StamfordProdRelease> GetStamfordProdReleases()
{
List<StamfordProdRelease> list = null;
string srtQry = "SELECT NVL(NULL, 0) ID," +
" DLOG.RELEASEID AS RELEASE_BUILD," +
" TRUNC (DLOGDET.DEPLOYDATE) AS PROD_DEPLOY_DATE," +
" DLOGDET.DEPLOYREQUEST AS BAAR_RFD," +
" DLOG.FILENAMEEXT_VC AS SCRIPT_NAME," +
" DLOG.VERSION," +
" DLOG.REQUEST," +
" DLOG.NOTE AS COMMENTS" +
" FROM ADM_DEPLOYMENTLOGDETAIL DLOGDET" +
" JOIN ADM_DEPLOYMENTLOG DLOG ON DLOG.LOGNO = DLOGDET.LOGNO;";
using (OracleConnection conn = new OracleConnection(Globals.Constants.AppConnectionStringReadOnly))
{
using (OracleCommand objCommand = new OracleCommand(srtQry, conn))
{
objCommand.CommandType = CommandType.Text;
DataTable dt = new DataTable();
OracleDataAdapter adp = new OracleDataAdapter(objCommand);
conn.Open();
adp.Fill(dt);
if (dt != null)
{
list = ConvertToStamfordProdRelease(dt).ToList();
}
}
}
return list;
}
My target is to insert records into a table.
Keep everything in one set of " and also you only need a single ; to end the SQL query outside of the double quotes.
private List<StamfordProdRelease> GetStamfordProdReleases()
{
List<StamfordProdRelease> list = null;
string srtQry = "SELECT NVL(NULL, 0) ID,
DLOG.RELEASEID AS RELEASE_BUILD,
TRUNC (DLOGDET.DEPLOYDATE) AS PROD_DEPLOY_DATE,
DLOGDET.DEPLOYREQUEST AS BAAR_RFD,
DLOG.FILENAMEEXT_VC AS SCRIPT_NAME,
DLOG.VERSION,
DLOG.REQUEST,
DLOG.NOTE AS COMMENTS
FROM ADM_DEPLOYMENTLOGDETAIL DLOGDET
JOIN ADM_DEPLOYMENTLOG DLOG ON DLOG.LOGNO = DLOGDET.LOGNO";
using (OracleConnection conn = new OracleConnection(Globals.Constants.AppConnectionStringReadOnly))
{
using (OracleCommand objCommand = new OracleCommand(srtQry, conn))
{
objCommand.CommandType = CommandType.Text;
DataTable dt = new DataTable();
OracleDataAdapter adp = new OracleDataAdapter(objCommand);
conn.Open();
adp.Fill(dt);
if (dt != null)
{
list = ConvertToStamfordProdRelease(dt).ToList();
}
}
}
return list;
}
Oracle 8i did not support standard ANSI SQL JOIN syntax.
That feature was introduced in Oracle 9i Release 2 (aka Oracle 9.2)
Quote from the chapter "What's New in SQL Reference"
SELECT [...] has new ANSI-compliant join syntax.
Don't combine the, strings put all in one.

MS SQL Invalid column name error

This code returns the following error:
"System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'a51'"
a51 is the correct value inside of the record I'm looking for in the EstablishmentCode column of the Establishments table. Account ID is used to find all entries on the Establishments table with that account ID and populate a dataset with Establishment Code values. Account ID value comes from a session variable. Then I use each of these values in a loop where each iteration calls a datareader while loop. Hope I explained this clearly, but I would gladly clarify more if needed. Here's my code.
myConnection.Open();
SqlCommand getEst = new SqlCommand("SELECT EstablishmentCode FROM Establishments WHERE AccountID = " + ID, myConnection);
da = new SqlDataAdapter(getEst);
ds = new DataSet();
da.Fill(ds);
int maxrows = ds.Tables[0].Rows.Count;
for (int x = 0; x < maxrows; x++)
{
getPhones = new SqlCommand("SELECT * FROM DispatcherPhones WHERE EstablishmentCode = " + ds.Tables[0].Rows[x].ItemArray.GetValue(0).ToString(), myConnection);
myReader = getPhones.ExecuteReader();
while (myReader.Read())
{
Response.Write("<section id='phone" + myReader["Phone"].ToString() + "' style='padding:20px'>");
Response.Write("<section>Phone Number<br><div class='phone'>" + myReader["Phone"].ToString() + "</div></section>");
Response.Write("<section>Location Code<br><div class='name'>" + myReader["EstablishmentCode"].ToString() + "</div></section>");
Response.Write("<section>Active<br><div class='name'>" + myReader["Active"].ToString() + "</div></section>");
Response.Write("<section class='flex phoneButtonSection'>");
Response.Write("<button type=\"button\" onclick=\"showPhoneForm('" + myReader["ID"].ToString() + "');\">CHANGE</button>");
Response.Write("<button type=\"button\" onclick=\"deletePhones('" + myReader["ID"].ToString() + "');\">DELETE</button>");
Response.Write("</section>");
Response.Write("</section>");
}
myReader.Close();
}
myReader.Close();
myConnection.Close();
String literals in SQL are denoted by single quotes ('s) which are missing for your value:
getPhones = new SqlCommand
("SELECT * " +
"FROM DispatcherPhones
"WHERE EstablishmentCode = '" +
// Here -------------------^
ds.Tables[0].Rows[x].ItemArray.GetValue(0).ToString() +
"'" // And here
, myConnection);
Mandatory comment: concatinating strings in order to create SQL statements may leave your code exposed to SQL injection attacks. You should consider using prepared statements instead.

How to insert new value autonumber by parameters to access

When I press insert, I receive the error: Syntax error in INSERT INTO statement
EmployeeID (Autonumber)
EmployeeName(Text)
Position(Text)
Address(Text)
OleDbDataAdapter ad;
DataSet ds;
DataTable dt;
protected void SetInsertParameters()
{
string sql = "INSERT INTO Employee(EmployeeName,Position,Address)"+
" VALUES (#EmployeeName,#Position,#Address)";
ad.InsertCommand = new OleDbCommand(sql, con);
OleDbParameter param = new OleDbParameter("#EmployeeName", OleDbType.VarChar);
param.SourceColumn = "EmployeeName";
param.SourceVersion = DataRowVersion.Current;
ad.InsertCommand.Parameters.Add(param);
param = new OleDbParameter("#Position", OleDbType.VarChar);
param.SourceColumn = "Position";
param.SourceVersion = DataRowVersion.Current;
ad.InsertCommand.Parameters.Add(param);
param = new OleDbParameter("#Address", OleDbType.VarChar);
param.SourceColumn = "Address";
param.SourceVersion = DataRowVersion.Current;
ad.InsertCommand.Parameters.Add(param);
}
void InsertNewValues()
{
dt = ds.Tables["Employee"];
DataRow row = dt.NewRow();
row[0] = txt_employeeID.Text;
row[1] = txt_name.Text;
row[2] = txt_position.Text;
row[3] = txt_address.Text;
dt.Rows.Add(row);
ad.Update(ds, "Employee");
ad.Fill(ds);
}
Position is a reserved word and must be bracketed:
"INSERT INTO Employee(EmployeeName,[Position],Address)"

MS-Access: SQL UPDATE syntax error, but why?

I'm getting a syntax error in this SQL, and can't seem to figure out why?
The SQL UPDATE returns this on the error:
UPDATE Tankstationer
SET Long='12.5308724', Lat='55.6788735'
WHERE Id = 2;
Here's my code:
foreach (var row in reader)
{
var id = reader.GetInt32(0);
var adress = reader.GetString(1);
var zip = reader.GetDouble(2);
var city = reader.GetString(3);
var adressToParse = adress + " " + zip + " " + city;
GMapGeocoder.Containers.Results result = Util.Geocode(adressToParse, key);
foreach (GMapGeocoder.Containers.USAddress USAdress in result.Addresses )
{
var google_long = convertNumberToDottedGoogleMapsValid(USAdress.Coordinates.Longitude);
var google_lat = convertNumberToDottedGoogleMapsValid(USAdress.Coordinates.Latitude);
Message.Text = "Lattitude: " + google_long + System.Environment.NewLine;
Message.Text = "Longitude: " + google_lat + System.Environment.NewLine;
string updatesql = "UPDATE Tankstationer SET Long='" +google_long+ "', Lat='" +google_lat+ "' WHERE Id = " +id+"";
OleDbCommand update = new OleDbCommand();
update.CommandText = updatesql;
update.Connection = conn;
reader = update.ExecuteReader();
Message.Text = "Done";
}
}
The error is probably because you are executing a reader, but your query does not return anything. Call update.ExecuteNonQuery() instead.
"Long" is a reserved word in Access. If you can't change the schema to call that column something else, put it in brackets:
UPDATE Tankstationer
SET [Long]='12.5308724', Lat='55.6788735'
WHERE Id = 2;
try using update.ExecuteNonQuery() instead of reader.
Saw other comments too late.
I don't use access often, but mine it's using <"> for text delimiter, not <'>
Try:
"id" is being set to Int32 (var id = reader.GetInt32(0);) but you are concatenating it to a string (WHERE Id = " +id+"";). Make sure that id is cast as a string value and not an int.