Format dates using Windows form in Visual Studio - visual-studio

I am trying to update the database with the following query, but I am having difficulty formatting dates. What should I do?
string query = "update employee_info set FirstName ='txtfirstName.Text',LastName ='txtlastName.Text' ,Address1='txt_address', City = 'combo_city' ,Country='combo_Country',ReportsTo='txt_reportTo' WHERE Bday='dtp_birthDate.Value.ToShortDateString()' and HireDate='dtp_hireDate.Value.ToShortDateString()'";

You should use a parameterized query instead. This gets you around having to format the strings for the where clause correctly and also prevents you from being vulnerable to SQL injection attacks (https://en.wikipedia.org/wiki/SQL_injection)
Something like this (the below sample has a shortened version of your query and lacks setting up a db connection).
strQuery = "update employee_info set FirstName=#firstName, LastName=#lastName WHERE Bday=#birthDate and HireDate=#hireDate";
cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#firstName", txtfirstName.Text);
cmd.Parameters.AddWithValue("#CompanyName", txtLastName.Text);
cmd.Parameters.AddWithValue("#birthDate", dtp_birthDate.Value);
cmd.Parameters.AddWithValue("#hireDate", dtp_hireDate.Value);
cmd.ExecuteNonQuery();

Related

Getting Second Order SQL Injection in Spring Hibernate

I am facing Second Order SQL Injection in the Spring-Hibernate application after scanning through the Checkmarx tool, I have gone through multiple questions in StackOverflow and in other platforms as well but did not get the right finding.
could you please look into the below code snip,
public String getOrderId(order_name){
String returnId= null;
Query query = entityManager.createNativeQuery("select order_id from order where order_name=?");
List<String> dataset = query.setParameter(1,order_name).getResultList();
if(dataset!=null){
returnId = dataset. Get(0);
}
return returnId;
}
In this above method, while calling getResultList(), getting a high vulnerability issue that, this method returns data flows through the code without being properly sanitized or validated, and eventually used in further database query in the method.
Earlier code was like this,
public String getOrderId(order_name){
String returnId= null;
String q = "select order_id from order where order_name="+order_name;
Query query = entityManager.createNativeQuery(q);
and directly it was used as a string append in query, which I have modified with set parameter,
Query query = entityManager.createNativeQuery("select order_id from order where order_name=?");
List<String> dataset = query.setParameter(1,order_name).getResultList();
but still after getting data from query.getResultSet(), it is asking for sanitizing and validating the data before use in further database query method.
and this return data is being used in further query like select * from return_Data where clause. (properly used in where clause to set parameter to avoid SQL injection).
and in the above query is used in another method where we pass return_Data as input to it.
could you please help here to know what checks and validation can be added to overcome this type of issue. Thanks in advance for prompt response.

VBA function to get windows user name [duplicate]

I would like to know if there is a way to get system username and use it directly in an MS Access query. I have made a parameter work within a query from a combo box on a form and I have also acquired system name in Access VBA using ENVIRON ("USERNAME").
Kindly let me know if this is possible.
You need to create a VBA function that returns the username, and then use the function in the query.
Public Function GetUserName() As String
' GetUserName = Environ("USERNAME")
' Better method, see comment by HansUp
GetUserName = CreateObject("WScript.Network").UserName
End Function
and
SELECT foo FROM bar WHERE myUserName = GetUserName();
My solution kept all the work in VB.
I used a variable for the windows login username and then created a SQL string with that variable inserted. Lastly, I updated the query behind the form to use this new SQL string.
The CHR(34) puts quotes around the name as it is now a string inside the SQLSTR and needs to be within a set of quotes.
If you have a complex SQL statement, write it in the QBE using a string for the name and all the other variables, then switch to the SQL view and replace it using a VBA variable as shown below.
MyName = Environ("username")
sqlstr = "SELECT * From Projects WHERE ( ((Projects.LeadEngineer)=" & Chr(34) & MyName & Chr(34) & " AND ActiveYN = True ));"
Forms![Main Form].RecordSource = sqlstr
You can use SYSTEM_USER if the query is being executed in a SQL Server, that will retrieve the user name connected to the database (for that, make sure you are not using fixed user name in your connection string)
Yes - you can use the 'CurrentUser' function in your query. Here I've included it as a field and criteria.
SELECT Field1, Field2, [CurrentUser] AS UserName FROM Table1 WHERE Field1 = [CurrentUser];

Visual Studio 2013 TableAdapter Config Wizard for Oracle

I'm a new user to setting up a query using the TableAdapter Config Wizard. I'm trying to run a simple query, and I thought it should look like this:
select id, name, val
from tableA
where name = #parm1 and val = #parm2
This does not work. How do I write the query and pass parameters using Oracle?
In Oracle, your parameters need to be prefixed with a colon, not an at sign:
select id, name, val
from tableA
where name = :parm1 and val = :parm2
On a related note, when you instantiate the parameters, unlike Sybase/SQL Server, you actually leave the identifier off of the parameter name:
OracleCommand cmd = new OracleCommand(sql, connection);
cmd.Parameters.Add(new OracleParameter("parm1", OracleDataType.Varchar));
I may have the Data Type enum slightly off, but you get the idea.

Update Does Not Work in VS2010 Using IDB2

I have no problem when trying to execute and insert or a delete SQL Command. However, this update command does not seems to work well and I am having a hard time to figure it out. Kindly help me please.
I am using an i Series or AS/400 database.
Imports IBM.Data.DB2
Imports IBM.Data.DB2.iSeries
Public conn As New iDB2Connection
Public str As String = "Datasource=10.0.1.11;UserID=edith;password=edith;DefaultCollection=impexplib"
Dim cmdUpdate As New iDB2Command
Dim sqlUpdate As String
conn = New iDB2Connection(str)
conn.Open()
sqlUpdate = "UPDATE impexplib.expusers SET loginDate=#loginDate, loginTime=#loginTime WHERE username=#username"
cmdUpdate.Parameters.Add("username", iDB2DbType.iDB2VarChar)
cmdUpdate.Parameters.Add("loginDate", iDB2DbType.iDB2Date)
cmdUpdate.Parameters.Add("loginTime", iDB2DbType.iDB2Time)
cmdUpdate.Parameters("username").Value = txtUsername.Text
cmdUpdate.Parameters("loginDate").Value = Now.ToString("d")
cmdUpdate.Parameters("loginTime").Value = Now.ToString("T")
cmdUpdate.Connection = conn
cmdUpdate.CommandText = sqlUpdate
cmdUpdate.ExecuteNonQuery()
conn.Close()
Please help me what I am doing wrong? The update code does not really work. Even a simple update of password does not work to.
Thanks!
Assuming no error messages anywhere, if no update is occurring, then the WHERE clause is not being satisfied. Make sure that the user name in DB2 exactly matches the parameter used in the WHERE clause. Very often, DB2 columns are CHAR, not VARCHAR or the other way round. You may also have a situation where the DB2 column is all upper case and the parameter is mixed case. Imagine the DB2 column has "FRED BLOGGS " and your parameter has "Fred Bloggs". This won't satisfy the WHERE clause and no rows will be updated.

Extracting timestamp field in Oracle vs MySQL from Grails-Groovy

I am using grails/groovy, and from my controller I am currently doing this for retrieving field from Mysql table containing datetime field
SimpleDateFormat Sformat = new SimpleDateFormat("yyyy-MM-dd");
String format_datenow = Sformat.format(new Date());
String format_dateprevious = Sformat.format(new Date() -31);
String markerCalcQuery =
"select sum(trans_cnt) as t_cnt, location from map2_data where fdate between '"+format_dateprevious+"' and '"+format_dateprevious+"' and res_id = "+res_id+" group by map2_data.location";
res_row=gurculsql.rows(markerCalcQuery);
The above query fails on Oracle11g with error
ORA-01843: not a valid month.
The error I feel is because MySQL stores date in this format: 2011-12-28 02:58:26 and Oracle stores date like this: 28-DEC-11 02.58.26.455000000 PM
How do I make the code generalised, one way is to make the database in Oracle store the date in the same format which I am thinking the way to handle this rather than from the code. If yes, how to change date format in the Oracle db?
Can I specify the format in the grails domain class for map2_data so that no matter what database it is we will have the datetime in the same format.
For several reasons (one being to code database independent - which is basically what you'd need ;-)), it is better to avoid creating SQL statements in your code. Try to use the Grails criteria DSL, e.g. something like
def criteria = YourDomainObject.createCriteria()
criteria.get {
between ('fdate', new Date()-31, new Date())
projections {
sum('trans_cnt')
groupProperty('location')
}
}
(ontested, but should help you get started).
If for some reason you can't use the criteria API, try the fallback to HQL (Hibernate Query Language). I'd always try to avoid to write plain SQL.
In Oracle, dates have their own type, they aren't strings. If you have a string, you should convert it to a date using the TO_DATE function.
String format_datenow = "TO_DATE('" + Sformat.format(new Date()) + "', 'YYYY-MM-DD')";
To make it work also in MySQL, you can create a stored function named TO_DATE that just returns its first argument.

Resources