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";
Related
I have query to just summary of total no of jobs running. now I just want some specific result if there is unique rows found like unique category id with assign job then ok with multiple record set. but no category found if is null then just only pass first record from datatable with modified text with 'ALL' as category name. can we achieve this result.
here is my query and some operations I'm doing with them.
string str = "";
DataTable dt = new DataTable();
str = "SELECT j.[JobID], p.[Id] As PreparedEmailID,p.[Title] AS 'PreparedEmailName',j.[CreatedOn],j.[CompletedOn],j.CategoryID,j.[SubscriberCount],j.[EmailsSent],c.[CategoryName] As SubscriberCategory,(SELECT TOP 1 [Message] FROM [LoggedMessages] WHERE [JobID] =j.[JobID] ORDER BY [LoggedMessageID] DESC) AS 'LoggedMessage',(SELECT [Name] FROM tbl_User_master u WHERE u.Id =j.UserID) As CreatedBy FROM [Jobs] AS j INNER JOIN [tbl_Email_master] AS p ON p.[Id] = j.[PreparedEmailID] INNER JOIN [tbl_User_master] AS u ON u.[Id]=j.[UserID] INNER JOIN tbl_Categories c ON c.Id = j.CategoryID OR (c.Id IS NOT NULL AND j.CategoryID IS NULL) where 1=1 ";
if (chk_date.Checked == true)
{
str += " and ( [CreatedOn] between '" + CommonLogic.Get_Date_From_String(txt_date_from.Text, 1);
str += "' and '" + CommonLogic.Get_Date_From_String(txt_date_to.Text, 2) + "' )";
}
if (string.IsNullOrEmpty(txttitle.Text.Trim()))
{
str += string.Empty;
}
else
{
str += " and p.Title like '%" + txttitle.Text.Trim() + "%'";
}
if (ddl_fromuser.SelectedItem.Text.ToString() == ".All")
{
str += string.Empty;
}
else
{
str += " and j.FromuserID = CONVERT(INT," + Convert.ToInt32(ddl_fromuser.SelectedValue.ToString()) + ")";
}
if (ddl_subcategories.SelectedItem.Text.ToString() == ".All")
{
str += string.Empty;
}
else
{
str += " and j.CategoryID = CONVERT(INT," + Convert.ToInt32(ddl_subcategories.SelectedValue.ToString()) + ")";
}
dt = obj.Get_Data_Table_From_Str(str);
if (dt.Rows.Count > 1)
{
dt.Rows[0]["SubscriberCategory"] = "ALL";
var topRows = dt.AsEnumerable().FirstOrDefault();
egrd.DataSource = topRows;
egrd.DataBind();
}
else
{
egrd.DataSource = dt;
egrd.DataBind();
}
ViewState["data"] = dt;
how ever this gives me error like no JobID found to this record set. whether it is still exists in record set.
please help me...
well I tried this solution but no success...……..
if (dt.Rows.Count > 1)
{
dt.Rows[0]["SubscriberCategory"] = "ALL";
var topRows = dt.AsEnumerable().GroupBy(j => j.Field<int>("JobID")).Select(j => j.First()).ToList();
egrd.DataSource = topRows;
egrd.DataBind();
}
it's gives me exception like DataBinding: 'System.Data.DataRow' does not contain a property with the name 'JobID'.
Just replace .ToList() with .CopyToDataTable() resolve my problem
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 + ","
}
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();
}
}
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()){
I have a prolem in my project when i get value from column in table. I create database by c# code.
This is my code:
public static int typeTransactionIncome = 1; // thu
public static int typeTransactionExpense = 2; // chi
public static int typeTransactionDebt = 3; // nợ
public static int typeTransactionLoan = 4; // cho vay
public static string tableNameCategory = "categories";
private static string createTableTransactionString = "CREATE TABLE IF NOT EXISTS \"transactions\" " + "(\"id\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,"
+ "\"name\" VARCHAR(140) ," + "\"amount\" FLOAT NOT NULL DEFAULT (0) ," + "\"type\" INTEGER NOT NULL ,"
+ "\"created_date\" DATETIME NOT NULL DEFAULT (CURRENT_DATE) ," + "\"displayed_date\" DATETIME NOT NULL DEFAULT (CURRENT_DATE) ,"
+ "\"cat_id\" INTEGER NOT NULL DEFAULT (0) ," + "\"with_person\" VARCHAR(50)," + "\"remind_date\" DATETIME,"
+ "\"remind_num\" INTEGER DEFAULT (0) ," + "\"note\" VARCHAR(140) ," + "\"status\" BOOL NOT NULL DEFAULT (0),"
+ "\"user_id\" INT NOT NULL DEFAULT (1))";
This is insert code: Insert some column, and there 2 insert menthod
public void insertNewIncome(string _name, string _note, double _amount, DateTime _displayedDate, int _catId, int _usertId)
{
try
{
openConnection();
SqliteCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO " + tableNameTransaction + "(type, name, note, amount, displayed_date, cat_id, user_id) values (#type, #name, #note, #amount, #displayed_date, #cat_id, #user_id)";
cmd.Parameters.Add("#type", typeTransactionIncome);
cmd.Parameters.Add("#name", _name);
cmd.Parameters.Add("#note", _note);
cmd.Parameters.Add("#amount", _amount);
cmd.Parameters.Add("#displayed_date", _displayedDate);
cmd.Parameters.Add("#cat_id", _catId);
cmd.Parameters.Add("#user_id", _usertId);
cmd.ExecuteNonQuery();
//MessageBox.Show("income");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
closeConnection();
}
}
public void insertNewDebt(string _debter, string _note, double _amount, DateTime _ngay_vay, DateTime _ngay_tra, int _user_id)
{
try
{
openConnection();
SqliteCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO " + tableNameTransaction + "(type, with_person, note, amount, displayed_date, remind_date, user_id) VALUES (#type, #with_person, #note, #amount, #displayed_date, #remind_date, #user_id)";
cmd.Parameters.Add("#type", typeTransactionDebt);
cmd.Parameters.Add("#with_person", _debter);
cmd.Parameters.Add("#note", _note);
cmd.Parameters.Add("#amount", _amount);
cmd.Parameters.Add("#displayed_date", _ngay_tra);
cmd.Parameters.Add("#remind_date", _ngay_tra);
cmd.Parameters.Add("#user_id", _user_id);
cmd.ExecuteNonQuery();
//MessageBox.Show("debt");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
closeConnection();
}
}
I was insert some records to table by insertNewDebt and insertNewIncome menthod, it was ok, not any error.
This is menthod that get all record in table:
public List<ItemTransaction> loadTransactionAll(DateTime _start_date, DateTime _end_date, int _user_id)
{
List<ItemTransaction> li = new List<ItemTransaction>();
openConnection();
SqliteCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT transactions.id AS master_id,transactions.name,transactions.amount,transactions.type,transactions.created_date, transactions.displayed_date,transactions.cat_id, transactions.with_person,transactions.remind_date,remind_num, transactions.note,transactions.status,transactions.user_id,categories.id,categories.name,categories.icon,categories.type,IFNULL(sub_amount,0) AS sub_amount "
+ "FROM transactions "
+ "LEFT JOIN categories ON transactions.cat_id = categories.id "
+ "LEFT JOIN ("
+ "SELECT sub_trans_id, IFNULL(SUM(sub_amount),0) AS sub_amount "
+ "FROM (SELECT trans_id AS sub_trans_id,SUM(amount) AS sub_amount "
+ "FROM sub_transactions "
+ "WHERE type = #type_income "
+ "GROUP BY sub_trans_id "
+ "UNION ALL SELECT trans_id AS sub_trans_id,SUM(amount) * -1 AS sub_amount "
+ "FROM sub_transactions "
+ "WHERE type = #type_expense GROUP BY sub_trans_id) GROUP BY sub_trans_id) ON sub_trans_id = master_id "
+ "WHERE (displayed_date BETWEEN #start_date AND #end_date) "
+ "AND transactions.user_id = #user_id "
+ "ORDER BY displayed_date DESC, transactions.type ASC, status ASC";
cmd.Parameters.Add("#type_income", DatabaseProccess.typeTransactionIncome);
cmd.Parameters.Add("#type_expense", DatabaseProccess.typeTransactionExpense);
cmd.Parameters.Add("#start_date", _start_date);
cmd.Parameters.Add("#end_date", _end_date);
cmd.Parameters.Add("#user_id", _user_id);
SqliteDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
ItemTransaction item = new ItemTransaction();
item.master_id = reader.GetInt32(0);
item.name = reader.GetString(1);
item.amount = reader.GetDouble(2);
item.type = reader.GetInt32(3);
item.created_date = reader.GetDateTime(4);
item.displayed_date = reader.GetDateTime(5);
item.cat_id = reader.GetInt32(6);
item.with_person = reader.GetString(7);
item.remind_date = reader.GetDateTime(8);
item.remind_num = reader.GetInt32(9);
item.note = reader[10].ToString();
item.status = reader.GetBoolean(11);
item.user_id = reader.GetInt32(12);
item.setCategory(reader.GetInt32(13), reader.GetString(14), reader.GetString(15), reader.GetInt32(16));
item.sub_amount = reader.GetDouble(17);
li.Add(item);
}
return li;
}
But when i execute insert:
insertNewIncome("", "note", "1000", DateTime.Today, 1, 1);
with 'name' field value = ""
I can not read 'name' field. Debug say:
view error screen shot here, please
And this is ItemTransaction class:
view ItemTransaction class here, please
I don't understand this error.
Please, thank
You're getting this error because name is NULL.
The following if statement would fix this:
if (reader(1) != null){
item.name = reader.GetString(1);
}
However if you're passing the value "", then this shouldn't be stored as NULL.
Check your database and see what the value is. Perhaps you have a trigger in place which updates "" to null.