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.
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 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.##"));
}
I have a simple .aspx login website and I use OleDB for local validation.
Here is my problem: After finding SQL Injection vulnerability, I decided to use parameters. But after using parameters my response is always "0" (Same as "Authenticated=false"). But if I don't use parameters, my response is "1" (Same as "Authenticated=true").
Here some pics while debugging:
Without parameters where the response=1 (Authenticated):
With code:
string idstr = Request.QueryString["id"];
idstr.Replace("''", "");
string passpath = Request.QueryString["password"];
passpath.Replace("''", "");
OleDbConnection connect = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source= C:\Users\hugow_000\Desktop\OSGS_Kantine_htm_design\Kantine_data.accdb; Persist Security Info = False;";
cmd.Connection = connect;
connect.Open();
cmd.CommandText = "select * from User_data where Stamnummer="+idstr+" and Wachtwoord="+ passpath;
OleDbDataReader read = cmd.ExecuteReader();
int code = 0;
while (read.Read())
{
code = code + 1;
}
if (code == 1)
{
Response.Redirect("~/AuthKeyGEN.aspx?Auth=true&id=" + idstr + "&password=" + passpath + "");
}
if (code > 1)
{
Response.Redirect("~/Login.aspx?response=0");
}
if (code < 1)
{
Response.Redirect("~/Login.aspx?response=0");
}
}
And with parameters where the response is 0 (Not Authenticated):
And with code:
string idstr = Request.QueryString["id"];
idstr.Replace("''", "");
string passpath = Request.QueryString["password"];
passpath.Replace("''", "");
OleDbConnection connect = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source= C:\Users\hugow_000\Desktop\OSGS_Kantine_htm_design\Kantine_data.accdb; Persist Security Info = False;";
cmd.Connection = connect;
connect.Open();
cmd.CommandText = "select * from User_data where Stamnummer=#idstr and Wachtwoord=#passpath";
cmd.Parameters.Add("#idstr", OleDbType.BSTR).Value = idstr;
cmd.Parameters.Add("#passpath", OleDbType.BSTR).Value = passpath;
OleDbDataReader read = cmd.ExecuteReader();
int code = 0;
while (read.Read())
{
code = code + 1;
}
if (code == 1)
{
Response.Redirect("~/AuthKeyGEN.aspx?Auth=true&id=" + idstr + "&password=" + passpath + "");
}
if (code > 1)
{
Response.Redirect("~/Login.aspx?response=0");
}
if (code < 1)
{
Response.Redirect("~/Login.aspx?response=0");
}
}
I am using the same credentials in both scenarios,
So why is my response always 0 if I use parameters in here?
Thanks in advance!
Doesn't look anything wrong but try using OleDbType.VarChar instead of OleDbType.BSTR since both the parameter are of string type; like
cmd.Parameters.Add("#idstr", OleDbType.VarChar).Value = idstr;
cmd.Parameters.Add("#passpath", OleDbType.VarChar).Value = passpath;
Also as a side note, instead of using select * use a count() query like below in which case you can use ExecuteScalar() rather than using ExecuteReader()
"select count(*) from User_data
where Stamnummer=#idstr and Wachtwoord=#passpath";
Ms Access uses ? as parameter place holders and the order is important (your order is correct). The parameter objects can be named as the name is ignored by the engine so it really does not matter but might make for more readable code. See OleDbCommand.Parameters as reference.
cmd.CommandText = "select 1 from User_data where Stamnummer = ? and Wachtwoord= ?";
Also change the parameter types as #Rahul had pointed out to VarChar.
General recommendations
Wrap your connection in a using block.This ensures your connection is always closed even when an Exception is encountered.
Like #Rahul said use ExecuteScalar instead of ExecuteReader. Use either COUNT(*) or hardcode 1 as the result: select 1 from User_data ...
Never ever store passwords as plain text, ever! This is horrible practice and makes for a very unsecure app. I have submitted a complete solution to creating a password hash that you could copy/paste and use directly.
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.
}
I use the following code for saving.Updating records to Oracle,
OracleConnection con = new OracleConnection(constr);
con.Open();
// Create the command.
OracleCommand cmd = new OracleCommand("", con);
cmd.CommandText = "<?xml version=\"1.0\"?>\n" +
"<ROWSET>\n" +
" <MYROW>\n" +
" <FIELD1>2</FIELD1>\n" +
" <FIELD2>zafar</FIELD2>\n" +
" </MYROW>\n" +
"</ROWSET>\n";
// Set the XML save properties.
KeyColumnsList = new string[1];
KeyColumnsList[0] = "FIELD1";
UpdateColumnsList = new string[1];
UpdateColumnsList[0] = "FIELD2";
cmd.XmlSaveProperties.KeyColumnsList = KeyColumnsList;
cmd.XmlSaveProperties.UpdateColumnsList = UpdateColumnsList;
cmd.XmlSaveProperties.RowTag = "MYROW";
cmd.XmlSaveProperties.Table = "testconn";
cmd.XmlSaveProperties.Xslt = null;
cmd.XmlSaveProperties.XsltParams = null;
rows = cmd.ExecuteNonQuery();
Console.WriteLine("rows: " + rows);
In the Field2 column I want to use select user from dual. I am not able to save current DB user.
The structure of data in the CommandText assumes that all values are literals. There is no way to have it recognize an inner query or expression. If you want to query the user you will have to do it separately and incorporate that into the data. This may be possible with the Xslt and XsltParams clauses.