Dynamically adding columns for SQL PreparedStatement - still safe against injection? - mysql

I am trying to prevent SQL injection in my Java program. I want to use PreparedStatements to do this, but I don't know the number of columns or their names in advance (the program allows administrators to add and remove columns from the tables). I'm new to this, so this may be a silly question, but I'm wondering if this approach is safe:
public static int executeInsert( String table, Vector<String> values)
{
Connection con;
try {
con = connect();
// Construct INSERT statement
int numCols = values.size();
String selectStatement = "INSERT INTO " + table + " VALUES (?";
for (int i=1; i<numCols; i++) {
selectStatement += ", ?";
}
selectStatement += ")";
PreparedStatement prepStmt = con.prepareStatement(selectStatement);
// Set the parameters for the statement
for (int j=0; j<numCols; j++) {
prepStmt.setString(j, values.get(j));
}
System.out.println( "SQL: " + prepStmt) ;
int result = prepStmt.executeUpdate();
con.close() ;
return( result) ;
} catch (SQLException e) {
System.err.println( "SQL EXCEPTION" ) ;
System.err.println( "Inserting values " + values + " into " + table);
e.printStackTrace();
}
return -1;
}
Basically I'm creating the String for the statement dynamically based on how many values are passed in (and therefore how many columns are in the table). I feel like it's safe because the PreparedStatement is not actually created until after this string is made. I may make similar functions that take in actual column names and incorporate them into the SQL statement, but these will be produced by my program and not based on user input.

Any time you have values like table being inserted into your query without escaping, you should test against a whitelist of known-good values. This prevents people from being creative and causing trouble. A simple dictionary or array of valid entries usually suffices.
Using a prepared statement is a good idea, but be sure the statement you're preparing doesn't allow for injections right from the start.

Related

How can I detect an access DB table with no columns?

I have a support tool I have written that allows me to create a table in MS Access DB file. Because of the support, I set it so it just creates the table without any columns defined. There is another part of the same program which allows column creations. However when I select the table in my list, I try to load the table. Since the table is empty, the system throws an error at the Fill (I understand the Select is the cause). Is there a way to ask if a table has any columns before trying to load that table?
public static bool ConnectToDatabase(string dbTable)
{
return ConnectToDatabaseWStr(dbTable, "Select * From `" + dbTable + "`");
}
public static bool ConnectToDatabaseWStr(string dbTable, string strSQL)
{
try
{
conn = new OleDbConnection(connectionString);
}
catch (Exception e)
{
LogFile.write(1, "DataAccess: error detected when creating OLEDBConnection.\nConnection string:\n" + connectionString + "\n" + e.ToString() + "\n");
}
try
{
dataAdapter = new OleDbDataAdapter(strSQL, conn);
dataAdapter.Fill(DataSetList[iCurrDataSetListIndex].DataSetInstance, dbTable);
This is easy if there are columns.
You can even go SELECT * from tableName where ID = 0
And then for each the column names. However, while the above will return 0 rows, the columns still do come through. However, without ANY columns, then the above will fail, and you would in theory have to know the "ID" column existed.
You can thus get oleDB provider to return a table as a "schema". This is table of ROWS of the defined table. Thus you can use this:
If NO rows are returned, then we don't have a table that lays out and defines the schema:
var strTableName = "tblHotels";
OleDbConnection myCon = new OleDbConnection(My.Settings.TestDB);
myCon.Open();
string[] SchemaParams = new[] { null, null, strTableName, null };
DataTable MyTable = myCon.GetSchema("Columns", SchemaParams);
if (MyTable.Rows.Count == 0)
// no columns for table
Debug.Print("no columns in table");
else
foreach (DataRow MyRow in MyTable.Rows)
Debug.Print(MyRow("Column_Name") + "->" + MyRow("Data_Type"));

Can't delete form database SQLGrammarException

I want to DELETE column from base in hibernate where my inserted -regBroj- parameter is same as one in a base.
This is my method in controller for deleting.But i constantly get
SQLGrammarException:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'BG026CH' in 'where clause'
This 'BG026CH' is value of regBroj that i use as a parameter to find vehicle in database and delete it.And i insert it in text area in adminPage.
public String izbrisi(String regBroj) {
List<Vozilo> lista = listaj();
Session s = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction t = s.beginTransaction();
for (int i = 0; i < lista.size(); i++) {
if (regBroj .equals(lista.get(i).getRegBroj())) {
String izbrisiquery = "DELETE FROM Korisnik WHERE brojLk=" + regBroj + "";
Query q = s.createQuery(izbrisiquery);
int a = q.executeUpdate();
t.commit();
return "adminPage";
}
}
t.commit();
return "error";
}
Please replace below string with these one
String izbrisiquery = "DELETE FROM Korisnik WHERE brojLk='" + regBroj + "'";
You should consider using prepared statements because they will automatically take care of escaping field values with quotes, and they will also protect you from SQL injection.
// obtain a Connection object using your Hibernate session, or through some other means
Connection conn = getDBConnection();
for (int i = 0; i < lista.size(); i++) {
if (regBroj .equals(lista.get(i).getRegBroj())) {
String izbrisiquery = "DELETE FROM Korisnik WHERE brojLk = ?";
PreparedStatement ps = conn.prepareStatement(izbrisiquery);
ps.setString(1, regBroj);
ps.executeUpdate();
t.commit();
return "adminPage";
}
}
To see how SQL injection works, or how a malicious user could wreck the Korisnik table, imagine that someone hacks the UI to pass a value of '' OR TRUE for brojLK. This is what the resulting DELETE statement would look like:
DELETE FROM Korisnik WHERE brojLk = '' OR TRUE
In other words, this injected query would drop your entire table! Prepared statements would choke on this input and a hacker would not get as far as executing the query.

Embedded SQL INSERT Using Dialog Boxes

I'm currently trying to insert new data into an existing table in my database using embedded SQL. I need to be able to enter my data in a dialog box and then have it shown back to me in a dialog box after it has executed.
My problem seems to be with the "s.executeUpdate(input);" for it tells me that I have an error in MySQL syntax. I'm not really sure how to fix it, or how to change the syntax. Help would be much appreciated!
Connection c = null;
try {
Class.forName("com.mysql.jdbc.Driver");
c = DriverManager.getConnection("jdbc:mysql://localhost:3306/company - final project", "root", "");
String query = "INSERT INTO works_on (ESSN, PNO, HOURS)" + "Values (?, ?, ?)";
Statement s = c.prepareStatement(query);
String input = JOptionPane.showInputDialog(null, "Info to be Inserted: ");
s.executeUpdate(input);
JOptionPane.showMessageDialog(null, "Data Inserted: " + input);
c.close();
}
catch (Exception e)
{
e.printStackTrace();
}
You're prepared statement requires 3 parameters, but you did not add any. need to call s.addXXX in the proper order to specify the 3 values to insert, wheres "XXX" is the appropriate type for the values

dynamic SQL execution and saving the result in flat file in SSIS

I want to create a SSIS package which writes a file with data generated by executing a SQL Statement. This generic package will be invoked by other packages passing in correct SQL as a variable.
Thus in the generic package :
I want to execute a dynamic SELECT query and fetch dynamic number of columns from a single database instance, the connection string does not per call and store the result into a flat file.
What would be an ideal way to accomplish this in SSIS.
What I tried :
The simplest solution that I could find was a writing a script task which would open a SQL connection , execute the SQL using SQLCommand, populate a datatable using the data fetched and write the contents directly to the file system using System.io.File and Release the connection.
I tried using OLE Database source with the SQLsupplied by a variable (with Validation set to false) and directing the rows into a Flat file connection. However due to the dynamic number and names of the columns I ran into errors.
Is there a more standard way of achieving this without using a script task?
How about this ... concatenate all field values into one field, and map AllFields to a field in a text file destination.
SELECT [f1]+',' + [f2] AS AllFields FROM [dbo].[A]
All of the "other"packages will know how to create the correct SQL. Their only contract with the "generic" package would be to eventually have only one field nameed "AllFields".
To answer your question directly, I do not think there is a "standard" way to do this. I believe the solution from Anoop would work well and while I have not tested the idea I wish I would have investigated it before writing my own solution. You should not need a script task in that solution...
In any case, I did write my own way to generate csv files from SQL tables that may run up against edge cases and need polishing but works rather well right now. I am looping through multiple tables before this task so the CurrentTable variable can be replaced with any variable you want.
Here is my code:
public void Main()
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
string TableName = Dts.Variables["User::CurrentTable"].Value.ToString();
string FileDelimiter = ",";
string TextQualifier = "\"";
string FileExtension = ".csv";
//USE ADO.NET Connection from SSIS Package to get data from table
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["connection manager name"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Read data from table or view to data table
string query = "Select * From [" + TableName + "]";
SqlCommand cmd = new SqlCommand(query, myADONETConnection);
//myADONETConnection.Open();
DataTable d_table = new DataTable();
d_table.Load(cmd.ExecuteReader());
//myADONETConnection.Close();
string FileFullPath = Dts.Variables["$Project::ExcelToCsvFolder"].Value.ToString() + "\\Output\\" + TableName + FileExtension;
StreamWriter sw = null;
sw = new StreamWriter(FileFullPath, false);
// Write the Header Row to File
int ColumnCount = d_table.Columns.Count;
for (int ic = 0; ic < ColumnCount; ic++)
{
sw.Write(TextQualifier + d_table.Columns[ic] + TextQualifier);
if (ic < ColumnCount - 1)
{
sw.Write(FileDelimiter);
}
}
sw.Write(sw.NewLine);
// Write All Rows to the File
foreach (DataRow dr in d_table.Rows)
{
for (int ir = 0; ir < ColumnCount; ir++)
{
if (!Convert.IsDBNull(dr[ir]))
{
sw.Write(TextQualifier + dr[ir].ToString() + TextQualifier);
}
if (ir < ColumnCount - 1)
{
sw.Write(FileDelimiter);
}
}
sw.Write(sw.NewLine);
}
sw.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception exception)
{
// Create Log File for Errors
//using (StreamWriter sw = File.CreateText(Dts.Variables["User::LogFolder"].Value.ToString() + "\\" +
// "ErrorLog_" + datetime + ".log"))
//{
// sw.WriteLine(exception.ToString());
//}
Dts.TaskResult = (int)ScriptResults.Failure;
throw;
}
Dts.TaskResult = (int)ScriptResults.Success;

SQL Syntax Problems

Im trying to do this:
String insertQuery=" DELETE FROM Accounts WHERE Username= " + Username + ";";
But im getting this error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'sam' in 'where clause'
Its getting the right username etc I know this by testing, I assume the syntax is wrong but im getting no syntax errors?
The table is called Accounts. The coloums are Username & Password,
You are missing single quotes. In your case(it's string) variable need to be wrapped in them or it'll be interpreted as column.
String insertQuery = "DELETE FROM Accounts WHERE Username = '" + Username + "'";
Recommendation:
Hence i recommend you to use placeholders to avoid this kind of problem. Don't forget to care about a security(SQL Injection for instance). It's worth to say that parametrized statements are also more human-readable, safer and faster as well.
I don't like "hardcoded" queries. Let's imagine a scenario if you had a table with ten columns and imagine how you query will look in this case: absolutely human-unreadable.
An usage of parametrized statements is always very efficient and comfortable practise. Your code looks good and becomes human-readable and what is "main" solution is much more safer and cleaner.
Have look at PreparedStatements. Basic example:
private final String deleteQuery = "DELETE FROM Accounts WHERE Username = ?";
public boolean deleteObject(String username) {
Connection c = null;
PreparedStatement ps = null;
try {
c = DataSource.getConnection();
ps = c.prepareStatement(deleteQuery);
ps.setString(1, username); // numbering starts with 1 not 0!
return ps.executeUpdate() > 0;
}
catch (SQLException ex) {
System.out.println("Error in deleteObject() method: " + ex.getMessage());
return false;
}
finally {
if (c != null) {
try {
c.close();
}
catch (SQLException ex) {
System.out.println("Error in closing conn: " + ex.getMessage());
}
}
}
}
If username is a varchar you need to add single quotes around the value in the where clause.
String insertQuery=" DELETE FROM Accounts WHERE Username= '" + Username + "';";
Since the value is not quoted its identifying the username, I'm assuming its Sam as a column.