java怎样获取mysql数据库字段内容
发布网友
发布时间:2022-04-08 06:44
我来回答
共2个回答
热心网友
时间:2022-04-08 08:13
你用的是什么数据库?
哦...呵呵刚没注意标题...
这个我以前写的,
假设你的用户名和密码都是root,你看下吧,不过在运行之前要先导入连接的那个jar文件
import java.sql.*;
public class TestConnectMySQL {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance(); // new一个Driver
conn = DriverManager.getConnection("jdbc:mysql://localhost/A?" //连接MySQL 不理解就记住
+ "user=root&password=root");
stmt = conn.createStatement(); //通过连接创建(createStatement)一个语句对象,不是new
rs = stmt.executeQuery("select * from pers"); //执行查询,返回一个结果集rs相当于一个游标
while (rs.next()) { //循环取得结果集(遍历)
System.out.println(rs.getString("b") + " " //把某一字段的内容 当成一个字符串拿出来,
+ rs.getString("c") + " " //也可以用其它的,比如rs.getInt("");等
+ rs.getString("d"));
}
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally { //不要忘了关闭
try {
if (conn != null) {
conn.close();
conn = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (rs != null) {
rs.close();
rs = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
热心网友
时间:2022-04-08 09:31
假设你的用户名和密码都是root,你看下吧,在运行之前要先导入连接的那个jar文件
import java.sql.*;
public class TestConnectMySQL {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance(); // new一个Driver
conn = DriverManager.getConnection("jdbc:mysql://localhost/A?" //连接MySQL 不理解就记住
+ "user=root&password=root");
stmt = conn.createStatement(); //通过连接创建(createStatement)一个语句对象,不是new
rs = stmt.executeQuery("select * from pers"); //执行查询,返回一个结果集rs相当于一个游标
while (rs.next()) { //循环取得结果集(遍历)
System.out.println(rs.getString("b") + " " //把某一字段的内容 当成一个字符串拿出来,
+ rs.getString("c") + " " //也可以用其它的,比如rs.getInt("");等
+ rs.getString("d"));
}
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally { //不要忘了关闭
try {
if (conn != null) {
conn.close();
conn = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (rs != null) {
rs.close();
rs = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}