方式1
package com.shujia.mysql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class MsyqlTest2 {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://master:3306/shujia", "root", "123456");
String sql ="select * from student where id = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,"1056");
ResultSet rs = ps.executeQuery();
while (rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String sex = rs.getString("sex");
System.out.println(id+"-"+name+"-"+age+"-"+sex);
}
rs.close();
ps.close();
conn.close();
}
}
方式2
package com.shujia.mysql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class MysqlTest {
public static void main(String[] args)throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://master:3306/shujia", "root", "123456");
Statement statement = conn.createStatement();
String sql="select * from student";
ResultSet rs = statement.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String sex = rs.getString("sex");
System.out.println(id+"-"+name+"-"+age+"-"+sex);
}
rs.close();
statement.close();
conn.close();
}
}