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

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();
}
}

Related

How to run SQL query concurrently in one by one

I am developing one page like Daily SMS Log for retrieving info regarding SMS run in background. I have this SQL code:
First Section
--SELECT ROW_NUMBER() OVER (ORDER BY RowId DESC)AS RowNumber,p.CampaignName,
-- p.MobileNo,
-- p.Message,
-- p.CharCount,
-- p.strSenderID as Sender,
-- u.strUserName as UserId,
-- ds.strDR as DeliveryStatus,
-- ds.strDiscription as Original_DRStatus,
-- m.strMessageType as MessageType,
-- CONVERT(varchar(20) , p.ReceiveTime) as ReceiveTime,
-- CONVERT(varchar(20) , p.SendTime) as SendTime,
-- CONVERT(varchar(20) , p.DoneTime) as DoneTime,
-- p.RootId as Root,
-- sp.ProviderName,
-- (CASE intAccountType WHEN 1 THEN 'Promotional' WHEN 2 THEN 'Transactional' WHEN 3 THEN 'OptIn' END) as AccountType
-- INTO #Results3
-- FROM NEWSMSLOG_2019_01..LOG_010119 p
-- INNER JOIN deliverstatus ds ON p.DeliveryStatus = ds.intDR_status inner join users u on u.id = p.userid
-- left join senderids b on b.id = p.senderid
-- left join messagetype m on m.intcode = p.messagetype
-- left join smppproviders sp on sp.RootId=p.RootId
-- where 1=1
Second Section
-- SELECT *
-- FROM #Results3
-- SELECT
-- CampaignName,MobileNo,Message,CharCount,Sender,UserId,DeliveryStatus,
-- Original_DRStatus,MessageType,ReceiveTime,SendTime,DoneTime,Root,ProviderName,AccountType
-- FROM #Results3
-- WHERE RowNumber BETWEEN('1' -1) * '109299' + 1 AND((('1' -1) * '109299' + 1) + '109299') - 1
Here when I uncomment the first line to where 1=1 then rows retrieved with success. And after that commenting up those line I uncomment second section then result shows bunch of rows. Now it's works fine in Management Studio.
Now I just want this result to grid view and here is my code:
protected void Get_Data()
{
try
{
string str = "";
DataTable dt = new DataTable();
str = "SELECT ROW_NUMBER() OVER (ORDER BY RowId DESC)AS RowNumber,p.CampaignName,";
str += "p.MobileNo,";
str += "p.Message,";
str += "p.CharCount,";
str += "p.strSenderID as Sender,";
str += "u.strUserName as UserId,";
str += "ds.strDR as DeliveryStatus,";
str += "ds.strDiscription as Original_DRStatus,";
str += "m.strMessageType as MessageType,";
str += "CONVERT(varchar(20), p.ReceiveTime) as ReceiveTime,";
str += "CONVERT(varchar(20), p.SendTime) as SendTime,";
str += "CONVERT(varchar(20), p.DoneTime) as DoneTime,";
str += "p.RootId as Root,";
str += "sp.ProviderName,";
str += "(CASE intAccountType WHEN 1 THEN 'Promotional' WHEN 2 THEN 'Transactional' WHEN 3 THEN 'OptIn' END) as AccountType";
str += " INTO #Results3 ";
str += " FROM NEWSMSLOG_2019_01..LOG_010119 p ";
str += " INNER JOIN deliverstatus ds ON p.DeliveryStatus = ds.intDR_status inner join users u on u.id = p.userid";
str += " left join senderids b on b.id = p.senderid";
str += " left join messagetype m on m.intcode = p.messagetype";
str += " left join smppproviders sp on sp.RootId = p.RootId";
str += " where 1 = 1 ";
if(ddl_users.SelectedItem.Text.ToString() == "All")
{
str += string.Empty;
}
else
{
str += " and p.userid = ' + CONVERT(varchar(5),"+ Convert.ToInt32(ddl_users.SelectedValue.ToString())+") + '";
}
if (ddl_sender.SelectedItem.Text.ToString() == "All")
{
str += string.Empty;
}
else
{
str += " and p.Senderid = '+CONVERT(varchar(10),"+Convert.ToInt32(ddl_sender.SelectedValue.ToString())+")+'";
}
if(!string.IsNullOrEmpty(txt_mobileno.Text.Trim()))
{
str += " and p.MobileNo like '' % '"+txt_mobileno.Text.Trim()+"' % ''";
}
else
{
str += string.Empty;
}
if(ddl_delevery.SelectedItem.Text.ToString() =="All")
{
str += string.Empty;
}
else
{
str += " and p.Deliverystatus in ('+CONVERT(varchar(10),"+Convert.ToInt32(ddl_sender.SelectedValue.ToString())+")+')'";
}
if(!string.IsNullOrEmpty(txt_CompaignName.Text.Trim()))
{
str += " and p.CampaignName like ''%'"+txt_CompaignName.Text.Trim()+"'%'' '";
}
else
{
str += string.Empty;
}
if(ddl_account.SelectedItem.Text.ToString() == "All")
{
str += string.Empty;
}
else
{
str += " and p.accounttype = '+CONVERT(varchar(2),"+Convert.ToInt32(ddl_account.SelectedValue.ToString())+")+'";
}
obj.Execute_Query(str);
string str1 = " SELECT * FROM #Results3";
str1 += " SELECT";
str1 += " CampaignName,MobileNo,Message,CharCount,Sender,UserId,DeliveryStatus,";
str1 += "Original_DRStatus,MessageType,ReceiveTime,SendTime,DoneTime,Root,ProviderName,AccountType";
str1 += " FROM #Results3";
str1 += " WHERE RowNumber BETWEEN('1' - 1) * '500' + 1 AND((('1' - 1) * '500' + 1) + '500') - 1";
str1 += " DROP TABLE #Results3";
dt = obj.Get_Data_Table_From_Str(str1);
ViewState["data"] = dt;
egrd.DataSource = dt;
egrd.DataBind();
ViewState["data"] = dt;
}
catch (Exception ex)
{
CommonLogic.SendMailOnError(ex);
}
}
But I have no records found in grid view. What's problem is that?
--------------------------Updated--------------------------------------------
namespace BulkSMSSystem.App_Code.DAL
{
public class DAL_General : DataAccess
{
public DataTable Get_Data_Table_From_Str(string str, string cnn_type = "NEWBULKSMS")
{
DataTable dt = new DataTable();
GetConnection(cnn_type);
dt = GetDataTableByQuery(str);
return dt;
}
public void Execute_Query(string str, string cnn_type = "NEWBULKSMS")
{
GetConnection(cnn_type);
GetExecuteNonQueryByStr(str);
}
public object Execute_Scalar(string str, string cnn_type = "NEWBULKSMS")
{
GetConnection(cnn_type);
object rtn = GetScalarOfStr(str);
return rtn;
}
---------------------------Updated 2-------------------------------------
public DataTable GetDataTableByQuery(string str_query)
{
try
{
mobj_SqlCommand.CommandText = str_query;
mobj_SqlCommand.CommandTimeout = mint_CommandTimeout;
mobj_SqlCommand.CommandType = CommandType.Text;
//mobj_SqlConnection.Open();
SqlDataAdapter adpt = new SqlDataAdapter(mobj_SqlCommand);
DataTable ds = new DataTable();
adpt.Fill(ds);
return ds;
}
catch (Exception ex)
{
throw ex;
}
finally
{
CloseConnection();
}
}
public void GetExecuteNonQueryByStr(string query_str)
{
try
{
mobj_SqlCommand.CommandType = CommandType.Text;
mobj_SqlCommand.CommandText = query_str;
mobj_SqlCommand.Connection = mobj_SqlConnection;
mobj_SqlCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
CloseConnection();
}
}
--------------------------Updated 3-----------------------------------
protected void GetConnection(string cnn_db = "NEWBULKSMS")
{
try
{
string Cnn_Str = "";
string ServerName = "SHREE-PC";
string DBUserName = string.Empty;
string DBPassword = string.Empty;
DBPassword += "c#" + Convert.ToChar(49);
string Database = cnn_db;
Cnn_Str = "Data Source=" + ServerName + "; UID=" + DBUserName + "; PWD=" + DBPassword + "; Database=" + Database+";Integrated Security = True";
//Cnn_Str = "Data Source=SHREE-PC;Initial Catalog=Project_DB_MNG;Integrated Security=True";
mstr_ConnectionString = Cnn_Str;
mobj_SqlConnection = new SqlConnection(mstr_ConnectionString);
mobj_SqlCommand = new SqlCommand();
mobj_SqlCommand.CommandTimeout = mint_CommandTimeout;
mobj_SqlCommand.CommandType = CommandType.StoredProcedure;
mobj_SqlCommand.Connection = mobj_SqlConnection;
mobj_SqlConnection.Open();
}
catch (Exception ex)
{
throw new Exception("Error initializing data class." + Environment.NewLine + ex.Message);
}
}
--------------------------Upadted 4--------------------------------------
As you are using temp table with one # sign it means that a temporary table will exists only during your session. However, if you create a temporary table with ##, then every user will be able to use that one, and none other can create a temp table with the same name, but it will be deleted when the owner session expired or disconnect.
So try to use in your code:
...
str += " INTO ##Results3 ";
...
And:
string str1 = " SELECT * FROM ##Results3";
str1 += " SELECT";
str1 += " CampaignName,MobileNo,Message,CharCount,Sender,UserId,DeliveryStatus,";
str1 += "Original_DRStatus,MessageType,ReceiveTime,SendTime,DoneTime,Root,ProviderName
,AccountType";
str1 += " FROM ##Results3";
str1 += " WHERE RowNumber BETWEEN('1' - 1) * '500' + 1 AND((('1' - 1) * '500'
+ 1) + '500') - 1";
str1 += " DROP TABLE ##Results3";

How to avoid every time initialization when value have greater than 0

I have a method that inserts a new record after checking whether it already exists or not.
Here is my method:
protected void btn_save_Click(object sender, EventArgs e)
{
string MobileNo = "";
string replaceValue = txt_mobile.Text.Replace(Environment.NewLine, "$");
string[] values = replaceValue.Split('$');
int uCnt = 0;
int sCnt = 0;
foreach (string item in values)
{
SaveRecord(item.Trim(),out MobileNo,out uCnt,out sCnt);
}
txt_mobile.Text = string.Empty;
if(uCnt > 0)
{
ClientScript.RegisterStartupScript(this.GetType(), "BulkSMS System", "alert('Mobile No(s) : "+MobileNo.TrimEnd(',')+" Already Exist');", true);
}
if(sCnt > 0)
{
ClientScript.RegisterStartupScript(this.GetType(), "BulkSMS System", "alert('" + sCnt + " Record(s) Inserted Successfully');", true);
}
Get_Data();
}
public void SaveRecord(string value, out string MobileNo, out int uCnt, out int sCnt)
{
uCnt = 0; //every time initialized to 0
sCnt = 0; //every time initialized to 0
MobileNo = "";
try
{
DataTable dt = new DataTable();
var dot = Regex.Match(value, #"\+?[0-9]{10}");
if (dot.Success)
{
string str = "SELECT TOP 1 [ID],[MobileNo] FROM[dbo].[whitelistdata]";
str += " WHERE [UserID] = '" + Convert.ToInt32(ddl_users.SelectedValue.ToString()) + "' AND [SenderId] = '" + Convert.ToInt32(ddl_senders.SelectedValue.ToString()) + "' AND [MobileNo] = '" + value + "'";
dt = obj.Get_Data_Table_From_Str(str);
if (dt.Rows.Count > 0)
{
uCnt++;
MobileNo += value + ",";
}
else
{
string str1 = "INSERT INTO [dbo].[whitelistdata]([UserID],[SenderId],[KeywordID],[MobileNo])";
str1 += "VALUES (" + Convert.ToInt32(ddl_users.SelectedValue.ToString()) + "," + Convert.ToInt32(ddl_senders.SelectedValue.ToString()) + ",1," + value + ")";
obj.Execute_Query(str1);
sCnt++;
}
}
}
catch (Exception ex)
{
CommonLogic.SendMailOnError(ex);
ClientScript.RegisterStartupScript(this.GetType(), "BulkSMS System", "alert('" + ex.Message.ToString() + "');", true);
}
}
The problem is every time it's set to 0 when method has been called I want to prevent them when previous value is greater than 0.
Please help me guys..
Please first identify which combination check-in database.
if UserID AND SenderId combination Match Then
string str = "SELECT TOP 1 [ID],[MobileNo] FROM[dbo].[whitelistdata]";
str += " WHERE [UserID] = '" + Convert.ToInt32(ddl_users.SelectedValue.ToString()) + "' AND [SenderId] = '" + Convert.ToInt32(ddl_senders.SelectedValue.ToString()) + "'";
if check the only UserID Match Then
string str = "SELECT TOP 1 [ID],[MobileNo] FROM[dbo].[whitelistdata]";
str += " WHERE [UserID] = '" +
Convert.ToInt32(ddl_users.SelectedValue.ToString()) +"'";
if UserID OR SenderId combination Match Then
string str = "SELECT TOP 1 [ID],[MobileNo] FROM[dbo].[whitelistdata]";
str += " WHERE [UserID] = '" + Convert.ToInt32(ddl_users.SelectedValue.ToString()) + "' OR [SenderId] = '" + Convert.ToInt32(ddl_senders.SelectedValue.ToString()) + "'";
if UserID AND SenderId AND MobileNo combination Match Then
string str = "SELECT TOP 1 [ID],[MobileNo] FROM[dbo].[whitelistdata]";
str += " WHERE [UserID] = '" + Convert.ToInt32(ddl_users.SelectedValue.ToString()) + "' AND [SenderId] = '" + Convert.ToInt32(ddl_senders.SelectedValue.ToString()) + "' AND [MobileNo] = '" + value + "'";
You need to use ref rather than out if you want to keep this design1. That means that the method can assume that the variables are already initialised and you're not forced to re-initialise them within the method:
public void SaveRecord(string value,out string MobileNo,ref int uCnt,ref int sCnt)
{
//uCnt = 0; //initialized by caller
//sCnt = 0; //initialized by caller
MobileNo = ""; //?
....
And at the call site:
SaveRecord(item.Trim(),out MobileNo,ref uCnt,ref sCnt);
You'll also want to do something about MobileNo too if you expect that to accumulate values rather than be over-written each time through the loop. Maybe make it a StringBuilder instead that you just pass normally (no ref or out) and let the SaveRecord method append to. out is definitely wrong for it.
1Many people would frown at a method that clearly wants to return values being declared void and making all returns via ref/out.
Something like:
public bool SaveRecord(string value)
{
...
Returning true for a new record, false for an existing record. I'd probably take out the exception handling from there and let the exception propagate higher before it's handled. Then the call site would be:
if(SaveRecord(item.Trim()))
{
sCnt++;
}
else
{
uCnt++;
MobileNo += item.Trim + ","
}

How to check the record in database exist or not if exist add to jtextarea else left blank (netbean)

Below is my code, which isn't working.
if can please provide example code or edit my code, TY
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/timetable", "root", "");
String sql1 = "select * from tt where day like '%monday%'";
String sql = "select * from tt where time = 8 ";
pst = con.prepareStatement(sql);
pst = con.prepareStatement(sql1);
rs = pst.executeQuery();
if (rs.next()) {
String sC = rs.getString("subjectcode");
String sN = rs.getString("subjectname");
String Ln = rs.getString("lecturer");
monday8to10.setText(sC + newline + "" + sN + newline + "" + Ln);
} else {
monday8to10.setText("");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/timetable", "root", "");
String sql1 = "select * from tt where day like '%monday%'";
String sql = "select * from tt where time = 10 ";
pst = con.prepareStatement(sql1);
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
String sC = rs.getString("subjectcode");
String sN = rs.getString("subjectname");
String Ln = rs.getString("lecturer");
monday10to12.setText(sC + newline + "" + sN + newline + "" + Ln);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
I believe to start, pst.executeQuery() requires an argument. You are currently no executing a query at all?
pst.executeQuery(sql1);
Seconds, you need to execute 1 query at a time:
String sql1 = "select * from tt where day like '%monday%'";
String sql = "select * from tt where time = 10 ";
becomes
String sql1 = "select * from tt where time = 10 and day like '%monday%'";
For example, I was just looking back at some of my old DB code.
query = "SELECT m.title, m.year_, m.rt_picture, m.imdb_picture, m.movie_id, u.user_score, u.user_id FROM movie_navigator.movies m, movie_navigator.userratings u WHERE m.movie_id=u.movie_id AND u.movie_id=" + movieId + " LIMIT " + queryPageSize + " OFFSET " + (queryPageSize*pageNumber) + ";";
try{
stmt = conn.createStatement();
results = stmt.executeQuery(query);
while(results.next()){

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)"

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

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);
}