Netbeans put data from a query into a variable - mysql

So I made a query, It's a inner join, the query is fine. But I want to put the data that is selected from the database into variables from an other class.
You see the code
Spel spel = null;
spel.setNaamSpel(spelUniekeNaam);
I didn't do it for all but is this the right way to do it?
public void laadSpel(String spelNaam)
{
String LAAD_SPELERS_SQL = "SELECT spel.naam, spel.aantalTeSpelenRondes, speler.naam, speler.kleur, speler.sector, speler.aantalZilverstukken, spelbord.type, spelbord.ecoWaarde, spelbord.stratWaarde, "
+ "spelbord.xcoord, spelbord.ycoord, spelbord.aantalKamelen, spelbord.kleur" +
"From spel INNER JOIN speler ON spel.naam = speler.Spel_naam" +
"INNER JOIN spelbord ON spel.naam = spelbord.Spel_naam" +
"WHERE spel.naam = '" + spelNaam + "'";
Statement statement;
Connection connection = PersistentieController.getInstance().getConnection();
try
{
statement = connection.createStatement();
ResultSet resultset = statement.executeQuery(LAAD_SPELERS_SQL);
while (resultset.next())
{
String spelUniekeNaam = resultset.getString("spel.naam");
String spelAantalRondes = resultset.getString("spel.aantalTeSpelenRondes");
String spelerNaam = resultset.getString("speler.naam");
String spelerKleur = resultset.getString("speler.kleur");
int spelerSector = resultset.getInt("speler.sector");
int spelerKrediet = resultset.getInt("speler.aantalZilverstukken");
String spelbordType = resultset.getString("spelbord.type");
int spelbordEco = resultset.getInt("spelbord.ecoWaarde");
int spelbordStrat = resultset.getInt("spelbord.stratWaarde");
int spelbordX = resultset.getInt("spelbord.xcoord");
int spelbordY = resultset.getInt("spelbord.ycoord");
int spelbordAantalKamelen = resultset.getInt(("spelbord.aantalKamelen"));
String spelbordKleur = resultset.getString("spelbord.kleur");
Spel spel = null;
spel.setNaamSpel(spelUniekeNaam);
}
statement.close();
} catch (SQLException e)
{
e.printStackTrace();
}
}

No.
Your other class Spel variable will not be present outside the while loop.
The spelUniekeNaam will be overwritten with every new record traversed in the resultset.
Please avoid using String concatenation for SQL queries as I pointed out in your earlier post here. This is just asking for an SQL Injection attack.

Related

Does MySQL support's creation of hidden column? [duplicate]

I am running a query on ID column but I don't want it to be visible in my frame/pane. How can I achieve this? Shall I make another table, is there a function in sql/mysql which allows to hide columns? I tried to google it but havent found anything yet.
Here is the code:
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int col = e.getColumn();
model = (MyTableModel) e.getSource();
String stulpPav = model.getColumnName(col);
Object data = model.getValueAt(row, col);
Object studId = model.getValueAt(row, 0);
System.out.println("tableChanded works");
try {
new ImportData(stulpPav, data, studId);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
public class ImportData {
Connection connection = TableWithBottomLine.getConnection();
public ImportData(String a, Object b, Object c)
throws ClassNotFoundException, SQLException {
Statement stmt = null;
try {
String stulpPav = a;
String duom = b.toString();
String studId = c.toString();
System.out.println(duom);
connection.setAutoCommit(false);
stmt = connection.createStatement();
stmt.addBatch("update finance.fin set " + stulpPav + " = " + duom
+ " where ID = " + studId + ";");
stmt.executeBatch();
connection.commit();
} catch (BatchUpdateException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null)
stmt.close();
connection.setAutoCommit(true);
System.out.println("Data was imported to database");
}
}
}
public class MyTableModel extends AbstractTableModel{
int rowCount;
Object data [][];
String columnNames [];
public MyTableModel() throws SQLException{
String query ="SELECT ID, tbl_Date as Date, Flat, Mobile, Food, Alcohol, Transport, Outdoor, Pauls_stuff, Income, Stuff FROM finance.fin";
ResultSet rs ;
Connection connection = TableWithBottomLine.getConnection();
Statement stmt = null;
stmt = connection.createStatement();
rs = stmt.executeQuery(query);
rs.last();
rowCount = rs.getRow();
data = new Object[rowCount][11];
rs = stmt.executeQuery(query);
for (int iEil = 0; iEil < rowCount; iEil++){
rs.next();
data[iEil][0] = rs.getInt("ID");
data[iEil][1] = rs.getDate("Date");
data[iEil][2] = rs.getFloat("Flat");
data[iEil][3] = rs.getFloat("Mobile");
data[iEil][4] = rs.getFloat("Food");
data[iEil][5] = rs.getFloat("Alcohol");
data[iEil][6] = rs.getFloat("Transport");
data[iEil][7] = rs.getFloat("Outdoor");
data[iEil][8] = rs.getFloat("Pauls_stuff");
data[iEil][9] = rs.getFloat("Income");
data[iEil][10] = rs.getFloat("Stuff");
}
String[] columnName = {"ID", "Date","Flat","Mobile"
,"Food","Alcohol","Transport", "Outdoor", "Pauls_stuff", "Income", "Stuff"};
columnNames = columnName;
}
This has solved my problem:
table.removeColumn(table.getColumnModel().getColumn(0));
I placed this in my class contructor. This lets remove the column from the view of the table but column 'ID' is still contained in the TableModel. I found that many people looking for an option to exclude specific column (like autoincrement) from SELECT statement in sql / mysql but the language itself doesn't have that feature. So I hope this solution will help others as well.
Don't put ID in the select part of the query
String query ="SELECT tbl_Date as Date, Flat, Mobile, Food, Alcohol, Transport,
Outdoor, Pauls_stuff, Income, Stuff FROM finance.fin";

My prepared statement not specified

I am doing a query to the database prepared statement but its just not coming out right.
i get this error when I print my statement.
com.mysql.jdbc.JDBC42PreparedStatement#157b62f9: SELECT * FROM 2015-wind WHERE TimeStamp BETWEEN '2015-01-01' AND '2015-01-25' AND ConnectingArea IN (** NOT SPECIFIED **)
10YAT-APG--L (I print my string and it give me an output).
Anybody knows whats going on here ?
public List<Wind2015> getResultsWind(String beginDate1, String endDate1, String[] connectingAreas1) throws Exception{
int count = 0;
List<Wind2015> myWind2015s = new ArrayList<>();
SimpleDateFormat readFormat = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy",
Locale.ENGLISH);
Date date2 = readFormat.parse(beginDate1);
Date date3 = readFormat.parse(endDate1);
String beginDate = new SimpleDateFormat("yyyy-MM-dd").format(date2);
String endDate = new SimpleDateFormat("yyyy-MM-dd").format(date3);
ArrayList<String> connectingArea = new ArrayList<>(Arrays.asList(connectingAreas1));
StringBuilder inputs = new StringBuilder();
for (int i = 0; i < connectingArea.size(); i++) {
if (i < connectingArea.size()-1) {
inputs.append("?,");
} else {
inputs.append("?");
}
}
String connectingAreaInputs = inputs.toString();
Connection connection = null;
PreparedStatement prepareStatement = null;
ResultSet myRs = null;
System.out.println(connectingAreaInputs);
try {
connection = getConnection();
String sql = "SELECT * FROM `2015-wind` WHERE `TimeStamp` BETWEEN ? AND ? AND `ConnectingArea` IN ("+ connectingAreaInputs +")";
prepareStatement = connection.prepareStatement(sql);
prepareStatement.setString(count+=1,beginDate);
prepareStatement.setString(count+=1, endDate);
System.out.println(prepareStatement);
for (String string : connectingArea) {
System.out.println(string);
count+=1;
prepareStatement.setString(count, string);
}
myRs = prepareStatement.executeQuery();
Wind2015 wind2015 = null;
while (myRs.next()) {
String timeStamp = myRs.getString("Timestamp");
String connectingArea1 = myRs.getString("ConnectingArea");
String value = myRs.getString("ActualWindEnergy");
wind2015 = new Wind2015(timeStamp, value, connectingArea1);
myWind2015s.add(wind2015);
}
return myWind2015s;
} finally {
close(connection, prepareStatement, myRs);
}
}
You're printing the prepared statement with this line:
System.out.println(prepareStatement);
before you assign value(s) to the dynamic placeholders in the IN (...) expression, so they're (correctly) displaying as "not [yet] specified".
Move the print statement to after the for loop that it currently sits before.

JDBC pass parameters to sql query

I have
employee(id, name, company, salary);
Need to display data for given id
public static void Connect(String conString, String username, String password, int id) throws SQLException{
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection(conString, username, password);
String query = "select * from employee where id = " + id + "" ;
ResultSet rs = null;
Statement stmt = null;
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
while(rs.next()){
String name = rs.getString("name");
String company = rs.getString("company");
int salary = rs.getInt("salary");
System.out.println("Name: " + name + "\tCompany: " + company + "\tSalary: " + salary);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But here we are passing the id directly. How can we pass it like parametrized queries (like how we pass ? during PreparedStatement)
in that case your query should be
String query = "select * from employee where id = ?";
instead of Statement you need to create PreparedStatement
PreparedStatement preparedStatement = conn.prepareStatement(query);
and then set your id to the prepared statement
preparedStatment.setInt(1, id);
finally execute the query
resultSet = preparedStatement.executeQuery();
It's old post but I would still like to add my answer.
I don't have enough reputation to comment on #prasad's answer, so I am adding small correction as separate answer. Actually, passing query inside praparedStatement.executeQuery() throws MySQLSyntaxErrorException because still it calls Statement.executeQuery instead of PreparedStatement.executeQuery(). And how do I know? I had to spent ample amount of time in figuring out this issue.
So use PreparedStatement.executeQuery() instead of PreparedStament.executeQuery(query).

How to delete row in database in MySQL using JSP?

This is my function. It gets two parameter id of the product and a name. the function delete with MySQL command a row in a database. I know the that there are missing lines in my code, I'm stuck and I don't know how to finish it. I also know that my SQL line is not correct. I'm not sure if combined the String "name" right.
public static deletePro(int cat, String name) {
DB db = new DB();
String sql = "delete from products where pname=+'name' and catid=" + cat;
ResultSet rs = db.getResultSet(sql);
try {
while (rs.next()) {
Products prod = new Products();
prod.setNamePro(rs.getString(name));
prod.setAmount(rs.getInt(cat));
}
rs.close();
db.closeCon();
} catch (SQLException e) {
e.printStackTrace();
}
return
}
String sql = "delete from products where pname=+'name' and catid=" + cat;
This should be:
String sql = "DELETE FROM products WHERE pname='" + name + "' and catid = " + cat;
And the preferred way is to use PreparedStatement, which would alleviate the pain of string manipulation in your query by using placeholders:
String sql = "DELETE FROM products WHERE pname= ? and catid = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, name);
ps.setInt(2, cat);
ps.executeUpdate();
Hope this helps.

Using ? in where clause for prepared statements

I have a method that returns an array list of search results from my database.
Instead of:
Select *
from employee
where first_name like ?
I would rather use:
Select *
from employee
where ? like ?
but I'm not sure if this is even possible? there's no errors when I compile it in eclipse but it keeps giving me blank values in the array. Is there something I'm doing wrong?
This is the method that gives me the blank value it works fine when I have where first_name like ? so I know the logic works.
public static ArrayList<String> AdvanceSearchFirstName(String selected, String searchTerm) {
String selectQuery = "select * from employee_info where ? like ?";
ArrayList<String> searchResults = new ArrayList<>();
try {
stmt = con.createStatement();
PreparedStatement ps = con.prepareStatement(selectQuery);
ps.setString(1, selected);
ps.setString(2, '%'+searchTerm+'%');
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String firstName = rs.getString("first_name");
String lastName = rs.getString("last_name");
String studentNumber = rs.getString("employee_number");
String combo = employeeNumber + " " + firstName + " " + lastName;
searchResults.add(combo);
}
} catch (SQLException e) {
e.printStackTrace();
}
return searchResults;
}
I've looked over a lot of posts so I'm pretty sure this hasn't been posted but I apologies if this is a double. I'm new to programming and sql so any help is appreciated.