Insert int from class to database (mysql) - mysql

I have two classes, from which I want one int number (first code) inserted into a database. The only thing I found so far is with a prepared statement, but I want the int from "freeparking" inserted into the database (second code) every hour. I have prepared a sleep thread already, which lets my second code initiate every full hour. But I am not sure how to insert the integer with my database. Thanks for your help in advance!
private void setFreieparkplätze(int freeparking) {
this.freeparking = freeparking;
}
int freeparking = vehiclenumber.getParking();
}
static Connection connection = null;
static String databaseName = "";
static String url = "jdbc:mysql://localhost:3306/tiefgarage?autoReconnect=true&useSSL=false" + databaseName;
static String username = "";
static String password = "";
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(url, username, password);
**PreparedStatement ps = connection.prepareStatement("INSERT Into parkinglot(Numbers) VALUES (?)");** // ???
int status = ps.executeUpdate();
if (status != 0) {
System.out.println("Database connected");
System.out.println("Record was inserted");
}

I repeat my comment as answer to make it visible to anyone.
The query to add an integer in a db shoould be like:
INSERT Into parkinglot(Numbers) VALUES ("+ getFreeparking() +");
Note that Numbers (table column) has to be integer type and getFreeparking() is just a getter for freeparking int variable.

Related

How can refresh a ResultSet in Java

I want to use a MySQL with JDBC in a loop, because I have to poll a table frequently for new data which comes in from other clients. But even if I close the ResultSet, the connection and the statement, is the old result at the next round still there. I cannot get a new result, unless I restart the program. What is my mistake?
I condensed the code for the necessary.
import java.sql.*;
public class Eventmgr {private static String in_text;
private static String in_typ;
private static Connection connection;
private static String URL = "jdbc:mysql://xxx.xxx.x.x:3306/xxxx";
private static String username = "xxx";
private static String password = "xxx";
public static void start() throws SQLException {
while(loop_count > 0) {
if (loop == false) {
loop_count = loop_count -1;}
connection = DriverManager.getConnection(URL, username, password);
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("select id, nummer, text, typ from inbox order by id asc limit 1") ;
while(rs.next()) {
in_id = rs.getString("id");
in_nummer = rs.getString("nummer");
in_text = rs.getString("text");
in_typ = rs.getString("typ");}
connection.close();
stmt.close();
rs.close();
System.out.println("still running");
}
}
}
Anybody has an idea what my problem is?
Thanks in advance
I am stupid, and it was my mistake...
The problem is. I check on the variable "in_id" and if there is no new result "while(rs.next())" dont deliver a new value, so I need to reset that variable with "in_id = null;" at the end of the loop.
Now it works...

Hibernate Query no work

I'm trying to update one row in my db using Query but I have no idea why it doesn't work.
I use this method:
#Override
public void updateImage(String avatar, int employeeId) {
Session session = HibernateUtil.getSessionFactory().openSession();
try {
Transaction transaction = null;
Query query = session.createQuery("UPDATE vt_employee SET emp_avatar=? WHERE id_employee=?");
query.setString(0, avatar);
query.setInteger(1, employeeId);
transaction = session.beginTransaction();
query.executeUpdate();
transaction.commit();
} catch (Exception e) {
e.getStackTrace();
} finally {
session.clear();
}
}
My values avatar and employeeId of course are not null or empty I checked it by display in console. My table in db is vt_employee and fields like emp_avatar and id_employee exist.
I checked in which place is problem and problem is in createQuery, if I tried to display arguments before session.createQuery then they displayed in console but after this one line they don't.
Could someone help to solve this problem?
Can you try with this.
public void updateImage(String avatar, int employeeId) {
String hql = "UPDATE vt_employee set emp_avatar =:avatar WHERE id_employee =:employeeId";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setParameter("avatar",avatar);
query.setParameter("employeeId",employeeId);
int i = query.executeUpdate();
if (i > 0) {
System.Out.println("Updated..") ;
}
}

Query MySQL DB using preparedStatement.setDate

public java.util.List<Tag> getAlltagsByDate(String date ){
DataSource dataSource = new DataSource();
Connection conn = dataSource.createConnection();
ResultSet resultSet = null;
PreparedStatement stmt = null;
Tag tags_Data = new Tag();
String query = "select * from tag_data where tag_data_date = ?";
try {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date nn =df.parse(date);
stmt = conn.prepareStatement(query);
stmt.setDate(1, java.sql.Date.valueOf(date));
resultSet = stmt.executeQuery(query);
I am getting an error
Can anyone help me with this,
I need to query mySQL db where date = input in html
No, skip the Date part; simply use the string. Let's see the value of (String date ).
MySQL is happy if you can end up with ... tag_data_date = '2015-12-11'.
If String date looks like '2015-12-11', then the conversion to Date is unnecessary.
I have presented a solution. As you have not mentioned much about your DB structure, so ,
Consider test as database name, and consisting of table tag_data having two columns id and tag_data_date as shown below.
CREATE TABLE `tag_data` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`tag_data_date` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Also consider data in table as
INSERT INTO `tag_data` (`id`, `tag_data_date`) VALUES
(1, '2015-12-20 00:00:00');
And your java class as below
public class JDBCPreparedStatementExample {
private static final String DB_DRIVER = "com.mysql.jdbc.Driver"; //mysql driver class
private static final String DB_CONNECTION = "jdbc:mysql://localhost:3306/test"; //connectionstring
private static final String DB_USER = "root"; //mysql username
private static final String DB_PASSWORD = "root"; //mysql password
public static void main(String[] argv) throws ParseException {
try {
getDateForDate("2015-12-20"); //time passed as arguement
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
//Method to interact with DB and print data,this can be changed to return value of List<Key> as per your requirement
private static void getDateForDate(String date) throws SQLException, ParseException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date dateCal =df.parse(date); // parse date in String to Date Object
String updateTableSQL = "select * from tag_data where tag_data_date = ?";
try {
//get DB connection
dbConnection = getDBConnection();
// Create preapared statement
preparedStatement = dbConnection.prepareStatement(updateTableSQL);
preparedStatement.setDate(1, new Date(dateCal.getTime()));//convert java.util.Date to java.sql.Date
// execute update SQL stetement
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g. resultSet.getString(2);
int id = resultSet.getInt("id");
Date tag_data_date = resultSet.getDate("tag_data_date");
System.out.println("Date: " + tag_data_date);
System.out.println("Comment: " + id);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
private static Connection getDBConnection() {
Connection dbConnection = null;
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(
DB_CONNECTION, DB_USER,DB_PASSWORD);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
}

SQL result convert into integer

I'm having trouble convert this String sql results into int. Can you guys tell how to accomplish this.
I'm doing this because I need this value set in to a JLabel that shows attendance count.
I've tried to search for the answer here, but I couldn't find it. Please can you guys help me with this problem?
public static int attendanceCount() throws ClassNotFoundException, SQLException {
String sql = "select count(accountNo) from attendance";
Connection conn = DBConnection.getDBConnection().getConnection();
Statement stm = conn.createStatement();
ResultSet rst = stm.executeQuery(sql);
return rst; // How do I convert this into integer?
}
This is what I need to accomplish.
private void setAttendanceTile() {
try {
int attendanceCount = AttendanceController.attendanceCount();
inHouseMembersLabel.setText(Integer.toString(attendanceCount));
} catch (ClassNotFoundException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
}
}
Or is there another way to accomplish this without doing this way?
Thanks.
get ResultSet.getInt(1):
int id = rst.getInt(1);
You could use ResultSet.getInt() method. It takes either a column index or a column name. Here's an example from Oracle.
In your case you would need the one which takes the index (note that index starts with 1, not 0).
As suggested earlier, try using .getInt() method.
Moreover, I would use PreparedStatement. It's important to use PreparedStatement, because it allows database to cache your queries.
Also, always close your Connection and ResultSet after using them.
public static int attendanceCount() throws ClassNotFoundException, SQLException {
final int COLUMN_NO = 1;
final String SQL = "select count(accountNo) from attendance";
Connection conn = DBConnection.getDBConnection().getConnection();
PreparedStatement stm = conn.prepareStatement(SQL);
ResultSet rst = stm.executeQuery();
int result = rst.getInt(COLUMN_NO);
try {
rst.close();
conn.close();
} catch (SQLException e) {} //ignore
return result;
}

How can I retrieve MySQL temporary tables meta data within a single connection in JDBC?

And once again I have found an issue that I don't know how to fight with. Let's assume we have the following testing code:
private static final String CREATE_TEMPORARY_TABLE =
"CREATE TEMPORARY TABLE T1 (\n" +
"\tA FLOAT(4, 1),\n" +
"\tB FLOAT(5, 2),\n" +
"\tC FLOAT,\n" +
"\tD INTEGER\n" +
") ENGINE = MEMORY;";
private final String[] SHOW_TABLE_TYPES = new String[] {
//"TABLE",
"VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM"
};
private void createTemporaryTable(Connection connection) throws SQLException {
final PreparedStatement statement = connection.prepareStatement(CREATE_TEMPORARY_TABLE);
statement.execute();
statement.close();
}
private void showTables(Connection connection) throws SQLException {
final ResultSet set = connection.getMetaData().getTables(null, null, null, SHOW_TABLE_TYPES);
while ( set.next() ) {
out.println(format("%s %s %s %s %s",
set.getString("TABLE_CAT"),
set.getString("TABLE_SCHEM"),
set.getString("TABLE_NAME"),
set.getString("TABLE_TYPE"),
set.getString("REMARKS")
));
}
set.close();
}
#Override
public void test(Connection connection) throws SQLException {
createTemporaryTable(connection);
showTables(connection);
}
Expected result is writing the T1 table meta data into the out stream. But nothing happens, and it seems that getTables() does not take into account the temporary tables. Don't know how I can resolve it... Is a work-around there? Your help is really very appreciated. Thanks a lot in advance.
MySQL sometimes does not provide support even for stupid things. There is no solution for the issue. Closed.