I want to read out a double and date from a SQLite Database with C#.
Database:
date: numeric
money: real
Code:
SQLiteConnection dbConnection = new SQLiteConnection("Data Source = " + nameDB + ".sqlite; Version = 3;");
dbConnection.Open();
String sql = $"SELECT * FROM banking";
SQLiteCommand command = new SQLiteCommand(sql, dbConnection);
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("date: " + Convert.ToDateTime( reader["date"]) );
Console.WriteLine("money: " + reader["money"]);
}
dbConnection.Close();
The problem is in my database data is this:
date: 28.06.2017 14:45:24
money: 20,50
And my output was this:
reader[date]: 28,06
reader[money]: 20
Ho can i say the reader to read the money as double and date as DateTime ?
reader.GetDouble(reader.GetOrdinal("money"));
reader.GetDateTime(reader.GetOrdinal("date"))
refer to Docs for all the available methods for SqliteDataReader
Use Parse methods for double and DateTime. Try like:
while (reader.Read())
{
var date =DateTime.Parse(reader["date"].ToString());
var money = double.Parse(reader["money"].ToString("0.##"));
}
Related
I want to display the contents of a certain column on a label, but when i get to this certain column which is in a date datatype.. it adds a "12:00:00 AM" and i want to remove it so that only the correct date and time pair will be joined together in a string. i am not allowed to alter the database table..
how can i eliminate that "12:00:00 AM" part of the string.. is it possible?
i am sure that its a date data type, but it gives one that looks like a datetime datatype.
well i'm clearly a newbie, and any suggestion or help is highly appreciated. Thank you so much.
the part of the database
when i retrieve a certain data in the db table, the label is not showing the exact same thing thats on the database
private void dbdateBtn_Click(object sender, EventArgs e)
{
//db read
string constring = "SERVER = localhost; user id = root; password =; database = mpdb";
string Query = "select * from mpdb.cicotbl where cico_no='" + this.textBox1.Text + "';";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string firstdate = myReader.GetString("CINd");
string seconddate = myReader.GetString("COUTd");
string time1 = myReader.GetString("CINt");
string time2 = myReader.GetString("COUTt");
dbdate1.Text = firstdate + " " + time1;
dbdate2.Text = seconddate + " " + time2;
}
conDataBase.Close();
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
}
I believe it's because the date is stored in the database as a date-time variable, a short fix is to use:
DateTime firstdate = DateTime.Parse(myReader.GetString("CINd"));
DateTime seconddate = DateTime.Parse(myReader.GetString("COUTd"));
string firstdatestring = firstdate.ToLongDateString();
string seconddatestring = seconddate.ToLongDateString();
string time1 = myReader.GetString("CINt");
string time2 = myReader.GetString("COUTt");
dbdate1.Text = firstdatestring + " " + time1;
dbdate2.Text = seconddatestring + " " + time2;
I'm using C# to do a request to a SQL server. The request need to be between 2 Timestamps (date and hour). The problem is if I put date only (2015-04-15) it works but if I put time behind (2015-04-15 16:00:00) it doesn't work anymore and show the error : "Close to '16' the syntax is incorrect."
I try different things but I can't find the way.
Here is my code:
DateTime Endtime = Convert.ToDateTime(DateTime.Now.Date.ToString("d") + " " + DateTime.Now.AddHours(1).Hour.ToString("00") + ":00:00");
DateTime Starttime = Convert.ToDateTime(DateTime.Now.Date.ToString("d") + " " + DateTime.Now.Hour.ToString("00") + ":01:00");
string time = string.Empty;
SqlConnection sqlCon = new SqlConnection("...");
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("SELECT COUNT(TimeStamp) FROM net WHERE Timestamp BETWEEN " + Starttime.ToString("yyyy-MM-dd hh:mm:ss") + " AND " + Endtime.ToString("yyyy-MM-dd hh:mm:ss"), sqlCon);
SqlDataReader reader = sqlCmd.ExecuteReader(); //Error comes from here
while (reader.Read())
{
time = reader[0].ToString();
}
Console.WriteLine(time);
Do you have any idea to make it?
How about making this a parameterized query, as in:
// Somewhere in your class declaration:
// Fixed parameterized query text as a constant.
private const string TimeRangeQuerySQL =
"SELECT COUNT(TimeStamp) FROM net WHERE Timestamp BETWEEN #starttime AND #endtime";
// ...
var cmd = new SqlCommand(TimeRangeQuerySQL, sqlCon);
cmd.Parameters.Add("#starttime", SqlDbType.DateTime).Value = Starttime;
cmd.Parameters.Add("#endtime", SqlDbType.DateTime).Value = Endtime;
var reader = sqlCmd.ExecuteReader();
// ...
Note that it is good practice to use parameterized queries instead of trying to assemble a query string yourself, so that you don't expose yourself to SQL injection attacks. You may want to read the story of little bobby tables.
Im new to c# here. I have a comboBox codes that enable user to choose month and dates. When user click cmdSend button, the program will retrieve the month & date form comboBox and call dbConnect.Select class function to do the select mysql statement.
private void cmdSend_Click(object sender, System.EventArgs e)
{
List<string>[] list;
list = dbConnect.Select(month_list.Text, year_list.Text);
printer_info.Rows.Clear();
for (int i = 0; i < list[0].Count; i++)
{
int number = printer_info.Rows.Add();
printer_info.Rows[number].Cells[0].Value = list[0][i];
printer_info.Rows[number].Cells[1].Value = list[1][i];
printer_info.Rows[number].Cells[2].Value = list[2][i];
printer_info.Rows[number].Cells[3].Value = list[3][i];
}
}
the retrieve database class:
public List<string>[] Select(string month,string year)
{
string query = "SELECT * FROM page_counter where month ='" + month + "' AND year ='" + year + "' ;";
//Create a list to store the result
List<string>[] list = new List<string>[4];
list[0] = new List<string>();
list[1] = new List<string>();
list[2] = new List<string>();
list[3] = new List<string>();
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
list[0].Add(dataReader["id"].ToString() + "");
list[1].Add(dataReader["month"].ToString() + "");
list[2].Add(dataReader["year"].ToString() + "");
list[3].Add(dataReader["page_count"].ToString() + "");
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return list to be displayed
return list;
}
else
{
return list;
}
}
However this code does not work, can someone advise me please?
EDITED:
string query = "SELECT * FROM page_counter where month = #month AND year = #year;";
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.Parameters.AddWithValue("#month",month);
cmd.Parameters.AddWithValue("#year",year );
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
list[0].Add(dataReader["id"].ToString() + "");
list[1].Add(dataReader["month"].ToString() + "");
list[2].Add(dataReader["year"].ToString() + "");
list[3].Add(dataReader["page_count"].ToString() + "");
}
//close Data Reader
dataReader.Close();
I have edited the code as suggested,However I have an error on the AddWithValue, it say : does not contain a definition for AddWithValue and no extension method AddWithValue, I have added the Data.MySqlClient reference but still remain the same. Please advise.
Problem 1 : You need to use SelectedItem property of the combobox to get the selected item from it.
Solution 1:
Replace This:
list = dbConnect.Select(month_list.Text, year_list.Text);
With This:
list = dbConnect.Select(month_list.SelectedItem.ToString(),
year_list.SelectedItem.ToString());
Problem 2:
i beilve that your Month and Year columns in your Database are INT columns.if they are INT columns you dont need to enclose the month and year parameter values within single quotes.
Solution 2:
Try This:
string query = "SELECT * FROM page_counter where month =
" + month + " AND year =" + year + " ;";
Suggestion : Your query is open to sql injection attacks i'd suggest to use Parameterised queries to avoid them.
Try This with Parameterised queries:
string query = "SELECT * FROM page_counter where month = #month AND year = #year;";
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.Parameters.AddWithValue("#month",month);
cmd.Parameters.AddWithValue("#year",year );
//Remaining same
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
list[0].Add(dataReader["id"].ToString() + "");
list[1].Add(dataReader["month"].ToString() + "");
list[2].Add(dataReader["year"].ToString() + "");
list[3].Add(dataReader["page_count"].ToString() + "");
}
//close Data Reader
dataReader.Close();
I need some guidance for parsing dates. My database table contains values
ID (int) and date (datetime: yyyy-mm-dd HH:mm:ss.fff format) and status
example
1000 & 2014-02-18 20:32:20.657 & 1
2000 & 2014-02-18 20:32:20.658 & 1
3000 & NULL & -1
I have a C# program that looks at this table for status=1 and date not null and want to insert ID and Date in the same format in a text file.
The text file should have
1000 2014-02-18 20:32:20.657
2000 2014-02-18 20:32:20.658
Here's the code.
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString))
{
connection.Open();
SqlCommand cmdSel = new SqlCommand(sqlSelNew, connection);
SqlDataReader reader1 = cmdSel.ExecuteReader();
while (reader1.Read())
{
DataSet ds = GetData(sqlSelNew);
CultureInfo _provider = CultureInfo.InvariantCulture;
ID = Convert.ToInt32(reader1["ID"].ToString());
string dtformat = #"yyyy/MM/dd HH:mm:ss.fff";
var d = DateTime.ParseExact(dateresized,dtformat , _provider);
using (StreamWriter sw = new StreamWriter(txtfilepath, true))
{
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine(ID + " " + d);
sw.Flush();
sw.Close();
}
I get "String was not recognized as a valid DateTime." error. How can I handle this?
Thanks
Rashmi
First, you shouldn't have to parse the date. You should simply be able to use reader.GetDateTime() to read that column and assign it. Second, why are you both filling up a DataSet and using a SqlDataReader to get the values directly? I'd expect one or the other but not both. Third, you ought to be wrapping your reader in a using statement as it implements IDisposable.
using (var reader1 = cmdSel.ExecuteReader())
{
while (reader1.Read())
{
var id = reader1.GetInt32(0);
var date = reader1.GetDateTime(1);
...
}
}
I'm facing a problem where every time I refresh my page, the loan paid will increase by 500. I understand that my logic is wrong, after 1 month from the loan application date, the 'loanPaid' will increase by 500 but what I want to happen is every next month it will increase by $500. If anyone who can help me with the logic. I would appreciate it. I was thinking of using some loop but not sure which one and how. I'm a freshman student only so please pardon my coding style. Thank you
public class LoanDAL
{
string connString = ConfigurationManager.ConnectionStrings["Oakhorizons"].ToString();
public LoanDAL()
{
//
// TODO: Add constructor logic here
//
}
public DataTable getAllLoanInfoDT()
{
using (SqlConnection conn = new SqlConnection(connString))
{
DataTable dt = new DataTable();
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = conn;
// cmd.CommandType = CommandType.StoredProcedure;
cmd2.CommandText = "SELECT DISTINCT purchaseDate FROM LoanPortfolio WHERE (custID LIKE 'OH00002') AND (loanType LIKE 'Personal Loan')";
cmd2.Parameters.AddWithValue("#custID", "OH00002");
cmd2.Parameters.AddWithValue("#loanType", "Personal Loan");
conn.Open();
string custID = "OH00002";
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd2;
da.Fill(dt);
int iMonthNo = int.Parse(System.DateTime.Now.Month.ToString());
DateTime dtDate = new DateTime(2000, iMonthNo, 1);
double dMonthNow = Double.Parse(dtDate.ToString("MM"));
LoanTableAdapters.LoanPortfolioTableAdapter loanAdapter = new LoanPortfolioTableAdapter();
string LoanDate = loanAdapter.RetrieveData(custID.ToString()).ToString();
string month = dt.ToString();
double dLoanDate = Double.Parse(LoanDate.Substring(3, 2));
if (dMonthNow > dLoanDate)
{
String sql = "UPDATE LoanPortfolio SET loanPaid = loanPaid + 500";
sql += "WHERE (loanType LIKE 'Personal Loan') AND (custID LIKE 'OH00002')";
cmd2.Connection = conn;
cmd2.CommandText = sql;
cmd2.ExecuteNonQuery();
}
conn.Close();
}
}
After edit:
public DataTable getAllLoanInfoDT()
{
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = conn;
// cmd.CommandType = CommandType.StoredProcedure;
cmd2.CommandText = "SELECT DISTINCT loanUpdateDate FROM LoanPortfolio WHERE (custID LIKE 'OH00002') AND (loanType LIKE 'Personal Loan')";
cmd2.Parameters.AddWithValue("#custID", "OH00002");
cmd2.Parameters.AddWithValue("#loanType", "Personal Loan");
conn.Open();
SqlDataReader myReader = cmd2.ExecuteReader();
DateTime loanUpdateDate = Convert.ToDateTime(myReader);
DateTime currDateTime = DateTime.Now;
int loanToBeAdded = (((currDateTime.Year - loanUpdateDate.Year) * 12) + currDateTime.Month - loanUpdateDate.Month) * 500;
if (loanToBeAdded > 0)
{
String sql = "UPDATE LoanPortfolio SET loanPaid = loanPaid + " + loanToBeAdded.ToString() + ", loanUpdateDate = " + DateTime.Now.ToString();
sql += " WHERE (loanType LIKE 'Personal Loan') AND (custID LIKE 'OH00002')";
//Execute the above query here
}
conn.Close();
using (SqlDataAdapter dAd = new SqlDataAdapter("SELECT * FROM LoanPortfolio where custID like 'OH00002'", conn))
{
DataTable dTable = new DataTable();
dAd.Fill(dTable);
return dTable;
}
}
}
You have done a lot of unnecessary things, some important checks missing and some performance inhibiting mistakes also in your code but I will not point them out here since you are a freshman and you will learn gradually.
The solution to your problem should be the following
Firstly create a new column in your "LoanPortfolio" table namely "LastUpdatedLoanPaidDate". The type should be Date for this column. This will store the date when you last added $500 to "loanPaid" column.
Set this column same as "purchaseDate" when you first add a row in your "LoanPortfolio" table. So initially "purchaseDate" and "LastUpdatedLoanPaidDate" will be same.
Fetch only "LastUpdatedLoanPaidDate" instead of "purchaseDate" as
cmd2.CommandText = "SELECT DISTINCT LastUpdatedLoanPaidDate FROM LoanPortfolio WHERE (custID LIKE 'OH00002') AND (loanType LIKE 'Personal Loan')";
Assuming that there will be just 1 record fetched from the above query, The following code should add $500 to "loadPaid" column once every month
//Fetch "LastUpdatedLoanPaidDate" here
//This will be "LastUpdatedLoanPaidDate" coming from database i.e. dt[0][0].ToString(). Hard-coded here for simplicity
string strLastUpdatedLoanPaidDate = "07/29/2013";
DateTime lastUpdatedLoanPaidDate = Convert.ToDateTime(strLastUpdatedLoanPaidDate);
DateTime currDateTime = DateTime.Now;
//This will make sure that all the previous purchases are also handled and not just previous month's
//This is important when you are implementing new logic on existing data
int loanToBeAdded = (((currDateTime.Year - lastUpdatedLoanPaidDate.Year) * 12) + currDateTime.Month - lastUpdatedLoanPaidDate.Month) * 500;
//If loadToBeAdded is zero then need not update database
if (loanToBeAdded > 0)
{
String sql = "UPDATE LoanPortfolio SET loanPaid = loanPaid + " + loanToBeAdded.ToString() + ", LastUpdatedLoanPaidDate = " + DateTime.Now.ToString();
sql += " WHERE (loanType LIKE 'Personal Loan') AND (custID LIKE 'OH00002')";
//Execute the above query here
}
There might be some things which I am missing depending upon your requirement. Also the update statement might need a tweak as I have not tested it but overall this should do the trick.
Hope this helped.
Regards,
Samar
You should also indicate in your table when you increased the loan for the last time and check this value, too. You could insert a new column lastLoanIncrease in the table LoanPortFolio as char(6) and save the month and year, when you increased it. Then before increasing again check for it.
You don't need a loop.
Your issue is in your conditional if
//DateTime loanDate = new DateTime(2000, 1, 18);
DateTime loanDueDate = Foo.GetLoanDueDate(loanId);
int loanDueMonth = loanDueDate.Month;
int currentMonth = DateTime.Now.Month;
if (currentMonth > loanDueMonth)
{
// update db
loanDate.AddMonths(1);
Foo.UpdateLoanDueDate(loanId, loanDate); // increase loan due date for next month so that the conditional is true next month.
}