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.
Related
I am facing an sql challenge here.
i have a database with a table called stockstable, & in this table, the only column with data type INT is quantity.
Below is my code where i am trying to update values in the table but i get an sql error which says :
java.sql.SQLSyntaxErrorException: Columns of type 'INTEGER' cannot hold values of type 'CHAR'.
But clearly i am writing an int in variable quantity into my table column quantity.
The order of the table columns is exactly as is my SQL Query.
Where might i be going wrong?
public void updateItemData() throws SQLException{
try{
Integer updatedQuantity = Integer.parseInt(jTextFieldQuantity.getText());
double updatedBuyingPrice = Double.parseDouble(jTextFieldBuyingPrice.getText());
double updatedSellingPrice = Double.parseDouble(jTextFieldSellingPrice.getText());
String updatedName = jTextFieldName.getText().toUpperCase();
String updatedID = jTextFieldItemID.getText();
String updatedDescription = jTextFieldDescription.getText().toUpperCase();
java.sql.Date newReceivingDate = new java.sql.Date(jDateChooserReceivingDate.getDate().getTime());
newReceivingDate.toString();
Class.forName("org.apache.derby.jdbc.ClientDriver");
java.sql.Connection con = DriverManager.getConnection("jdbc:derby:C:\\Program Files\\ERS\\Database\\EmployeeDB", "axle","axle");
String list5 = "UPDATE STOCKSTABLE SET name = '"+updatedName+"',"
+ "description = '"+updatedDescription+"',"
+ "id = '"+updatedID+"',"
+ "quantity = '"+updatedQuantity+"',"
+ "systemdate = '"+systemDate+"',"
+ "receivingdate = '"+newReceivingDate+"',"
+ "buyingprice = '"+updatedBuyingPrice+"',"
+ "sellingprice = '"+updatedSellingPrice+"' where id = '"+jTextFieldItemID.getText()+"'";
////////////////////////*********************************createStatement
Statement stmt = con.createStatement();
JOptionPane.showMessageDialog(null, "QUANTITY :"+updatedQuantity);
stmt.executeUpdate(list5);
JOptionPane.showMessageDialog(null, "HERE");
//ResultSet rs = stmt.executeQuery(list5);
///////////////////////**********************************end of createStatement
//jTableStocks.setModel(DbUtils.resultSetToTableModel(rs));
refresh();
jButton5.setText("ADD TO STOCK");
JOptionPane.showMessageDialog(null, "Update Successful");
} catch (ClassNotFoundException ex) {
JOptionPane.showMessageDialog(null, "Update Error!");
Logger.getLogger(MainMenu.class.getName()).log(Level.SEVERE, null, ex);
}
}
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 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";
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 + ","
}
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()){