java读取MySQL数据库

java读取MySQL数据库,第1张

在String

value

=

rs.getString("name")

之前要先rs.next()一下

你用这个来判断密码错误?

if(!rs.isBeforeFirst()){

JOptionPane.showMessageDialog(frame,

"Wrong

password!")

}

isBeforeFirst()

的意思是:获取光标是否位于此

ResultSet

对象的第一行之前。

用JDBC连接数据库,然后用sql语句。要导入mysql的驱动包。

import java.sql.*

public class TestMySql {

static Connection con = null// 声明Connection对象

static Statement sql = null

static ResultSet res = null

public static void main(String[] args) {

TestMySql c = new TestMySql()

con = c.getConnection()

try {

sql = con.createStatement()

res = sql.executeQuery("select * from dept")

//sql语句,我数据库里有张dept表

while (res.next()) {//输出结果

System.out.print(res.getString(1) + "<——>")

System.out.print(res.getString(2) + "<——>")

System.out.print(res.getString(3) )

System.out.println()

}

} catch (SQLException e) {

e.printStackTrace()

} finally {

try {

if (res != null) {

res.close()

res =null

}

if (sql != null) {

sql.close()

sql =null

}

if (con != null) {

con.close()

con =null

}

} catch (SQLException e) {

e.printStackTrace()

}

}

}

public Connection getConnection() {

try {

Class.forName("com.mysql.jdbc.Driver")

// 加载oracleJDBC驱动

System.out.println("数据库驱动加载成功")

} catch (ClassNotFoundException e) {

e.printStackTrace()

}

try {// 通过访问数据库的URL获取数据库连接对象

con = DriverManager.getConnection(

"jdbc:mysql://localhost:3306/mydata", "root", "qwer1234")

//mydata为mysql名字

System.out.println("数据库连接成功")

} catch (SQLException e) {

e.printStackTrace()

}

return con// 按方法要求返回一个Connection对象

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/6106224.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-15
下一篇 2023-03-15

发表评论

登录后才能评论

评论列表(0条)

保存