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

JDBC连接mysql<PreparedStatement>

2016-02-19 12:01 525 查看
package com.buaa.demo1;

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

public class Test01 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/shopping?characterEncoding=utf8";
String username = "root";
String password = "zhen5296";
String sql = "select * from person";
try{
Class.forName(driver);
conn = DriverManager.getConnection(url,username,password);
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
Person person = new Person();
while(rs.next()){
person.setId(rs.getInt(1));
person.setName(rs.getString(2));
person.setAge(rs.getInt(3));
person.setPhoto(rs.getString(4));
System.out.println(person.toString());
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: