第2个回答 推荐于2018-03-22
这是java中连接MySQL的代码
public class PreparedStatementDemo {
static Properties porp;
private static String url;
private static String user;
private static String password;
public static void main(String[] args){
Connection conn = null;
Statement st = null;
ResultSet rs = null;
porp = new Properties();
PreparedStatement stmt = null;
try {
porp.load( new FileInputStream("jdbc.properties"));
url = porp.getProperty("chap20.url");
user = porp.getProperty( "chap20.user");
password = porp.getProperty("chap20.password");
Class.forName(porp.getProperty( "chap20.Driver"));
conn = DriverManager.getConnection(url,user,password);
st = conn.createStatement() ;
stmt = conn.prepareStatement( "insert into student values(?,?,?)");
stmt.setInt(1,130610);
stmt.setString(2,"zhaoli");
stmt.setInt(3,19);
stmt.executeUpdate();
stmt.clearParameters();
rs = st.executeQuery("select * from student");
while(rs.next()){
System.out.print(rs.getInt(1)+"\t");
System.out.print(rs.getString(2)+"\t");
System.out.println(rs.getInt(3));
}
} catch (Exception e) {
e.printStackTrace();
}
finally{
if(stmt!=null){
try {
stmt.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();
}
}
}
}
}本回答被网友采纳