gpt4 book ai didi

java - 从 mysql 获取日期

转载 作者:行者123 更新时间:2023-11-30 03:22:52 26 4
gpt4 key购买 nike

如何将 mysql 数据库中的日期转换为 Java 中的变量?这是我到目前为止所尝试过的:

try {
Connection connection = DriverManager.getConnection(database, user, pass);
Statement statement = connection.createStatement();
String sql = "select mhs.angkatan from t_nilai nilai JOIN t_mahasiswa mhs ON nilai.nim = mhs.nim WHERE mhs.nim = '" + txt_nim + "'";
ResultSet resultSet = statement.executeQuery(sql);
Date angkatan = resultSet.getDate("angkatan");
resultSet.close();
statement.close();
connection.close();
} catch (Exception e) {
System.err.println(e.getMessage());
JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}

最佳答案

检查this请张贴出来。那里有一个例子

___更新___

(下面的代码取 self 上面给出的链接。感谢 Balkrishna Rawool 的提醒)

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Main {
public static Connection getMySQLConnection() throws Exception {
String driver = "org.gjt.mm.mysql.Driver";
String url = "jdbc:mysql://localhost/databaseName";
String username = "root";
String password = "root";
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}

public static void main(String args[]) {
ResultSet rs = null;
Connection conn = null;
Statement stmt = null;
try {
conn = getMySQLConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery("select timeCol, dateCol, dateTimeCol from dateTimeTable");
while (rs.next()) {
java.sql.Time dbSqlTime = rs.getTime(1);
java.sql.Date dbSqlDate = rs.getDate(2);
java.sql.Timestamp dbSqlTimestamp = rs.getTimestamp(3);
System.out.println("dbSqlTime=" + dbSqlTime);
System.out.println("dbSqlDate=" + dbSqlDate);
System.out.println("dbSqlTimestamp=" + dbSqlTimestamp);

java.util.Date dbSqlTimeConverted = new java.util.Date(dbSqlTime.getTime());
java.util.Date dbSqlDateConverted = new java.util.Date(dbSqlDate.getTime());
System.out.println("in standard date");
System.out.println(dbSqlTimeConverted);
System.out.println(dbSqlDateConverted);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

关于java - 从 mysql 获取日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30936413/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com