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.
Related
im trying to get the data form this jFrame including the data from the jTable and please consider that the values of the table ( the rows number might change )
I've written this code but its not working and I'm a beginner so please if anyone can help
ive tried this code and no values are being inserted to mysql Table
private void SaveActionPerformed(java.awt.event.ActionEvent evt) {
try{
Class.forName("com.mysql.jdbc.DriverManager");
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/StudentAttendence","root","Qjrq3Y3d38");
int rows=jTable1.getRowCount();
for(int row = 0; row<rows; row++)
{
String StudentID = (String)jTable1.getValueAt(row, 0);
String Student_Name = (String) jTable1.getValueAt(row, 1);
String Subject_ = (String)subject.getSelectedItem().toString();
String Date_ = (String)date.getDateFormatString();
Boolean Attendance = (boolean) jTable1.getColumnSelectionAllowed();
String query = "Insert into attendance(StudentID,Student_Name,Subject_,Date_,Attendance) values ('"+StudentID+"','"+Student_Name+"','"+Subject_+"','"+Date_+"','"+Attendance+"')";
pst = con.prepareStatement(query);
pst.execute();
}
JOptionPane.showMessageDialog(null, "Successfully Save");
}
catch(Exception e){
JOptionPane.showMessageDialog(this,e.getMessage());
}
}
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";
public int getdata(String startDate, String endDate) {
PreparedStatement ps;
int id = 0;
try {
/*
* SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
* java.util.Date startDat = formatter.parse(startDate);
* java.util.Date endDat = formatter.parse(endDate);
*/
// ps = connection.prepareStatement("select * from project.order Where PO_Date Between " + startDate + "' AND '" + endDate + "'");
//ps = connection.prepareStatement("select * from project.order where PO_Date between ? AND DATE_ADD( ?, INTERVAL 1 DAY) ");
//ps = connection.prepareStatement("SELECT * FROM project.order WHERE PO_Date between ? AND ?");
ps = connection.prepareStatement("SELECT * FROM project.order WHERE PO_Date >= ? AND PO_Date <= ?");
//ps = connection.prepareStatement("SELECT * FROM project.order WHERE PO_Date(now())>= ? AND PO_Date(now())<=?");
/*
* ps.setDate(1, new java.sql.Date(startDate)); ps.setDate(2, new
* java.sql.Date(endDate.getTime()));
*/
ps.setString(1, startDate);
ps.setString(2, endDate);
ResultSet rs = ps.executeQuery();
// System.out.println("value of rs "+rs);
while (rs.next()) {
ArrayList<String> arrlist = new ArrayList<String>();
System.out.println(rs.getString(2));
System.out.println(rs.getInt(1));
System.out.println(rs.getString(4));
System.out.println(rs.getString(5));
System.out.println(rs.getString(6));
System.out.println("***************");
// System.out.print(rs.getDate("endDate"));
Iterator<String> itr = arrlist.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
rs.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return id;
}
}
I tried to solve but I am getting out except last date means endDate which we give as a input.
I tried around 5 different queries but still I am getting the same.
In MySQL, the DATE type maps to the Java class java.sql.Timestamp. So you should be working with this type to build your query, and not java.util.Date. Here is code which generates the two timestamps you will need:
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date startDate = formatter.parse(startDate);
java.util.Date endDate = formatter.parse(endDate);
java.sql.Timestamp start = new Timestamp(startDate.getTime());
java.sql.Timestamp end = new Timestamp(endDate.getTime());
Then use your first BETWEEN query to get your result:
PreparedStatement ps = con.prepareStatement("SELECT * FROM project.order
WHERE PO_Date BETWEEN ? AND ?");
ps.setTimestamp(1, start);
ps.setTimestamp(2, end)
Note here that I am using a parametrized PreparedStatement, which avoids (or at least greatly lessens) the possibility of SQL injection.
Try this
SELECT * FROM project.order po
WHERE po.PO_Date IS NOT NULL
AND TO_DATE(PO_Date, 'DD/MM/RRRR') >=
TO_DATE('17/02/2015', 'DD/MM/RRRR')
AND TO_DATE(PO_Date, 'DD/MM/RRRR') <=
TO_DATE('20/06/2015', 'DD/MM/RRRR');
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.
I using Linq DataContext.Log and I want to save sql command with parameters. how may I do this??
Now to log is writing:
SELECT [t0].[Id_User],
[t0].[FirstName], [t0].[LastName],
[t0].[UserName], [t0].[Password],
[t0].[District_Id], [t0].[Active],
[t0].[MobileDevice_Id],
[t0].[IsMobile], [t0].[IsWWW],
[t0].[IsWholesaler], [t0].[Acc_Admin],
[t0].[Warehouse_Id], [t0].[PIN],
[t0].[ValidFrom], [t0].[ValidTo],
[t0].[IsExternal], [t0].[UserType],
[t0].[DefaultDepartment_Id],
[t0].[Code], [t0].[RowsOnPage],
[t0].[ClientGroup_Id],
[t0].[ClientGroup2_Id],
[t0].[ServerHash],
[t0].[CanOrderInPacks], [t0].[Email],
[t0].[IsAdmin],
[t0].[HasAccessToAllInferiorsData],
[t0].[IsSupplier], [t0].[Position],
[t0].[syncstamp] AS [Syncstamp],
[t0].[Source], [t0].[Deleted],
[t0].[DefaultClient_Id] FROM
[dbo].[Users] AS [t0] WHERE
([t0].[UserName] = #p0) AND
([t0].[Deleted] = #p1)
I want write #p0 and #p1 to log
Param value can be read by following line of code
var results = db.calltodatabase.Where(pradicate);
IQueryable query = results;
DbCommand dbCommand = dataContext.GetCommand(query);
var result = new SqlQueryText();
result.Text = dbCommand.CommandText;
int nParams = dbCommand.Parameters.Count;
result.Params = new ParameterText[nParams];
for (int j = 0; j < nParams; j++)
{
var param = new ParameterText();
DbParameter pInfo = dbCommand.Parameters[j];
param.Name = pInfo.ParameterName;
param.SqlType = pInfo.DbType.ToString();
object paramValue = pInfo.Value;
if (paramValue == null)
{
param.Value = null;
}
else
{
param.Value = pInfo.Value.ToString();
}
result.Params[j] = param;
}