您的位置:首页 > 数据库 > MySQL

某网友的javaMYSQL代码

2013-10-09 11:30 337 查看
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();

}

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: