java连接数据库基础操作实例代码,备用。
public static void main(String[] args) {
try{
//mysql
String URL="jdbc:mysql://127.0.0.1:3306/mytest?useSSL=false&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true";
//oracle
//String URL="jdbc:oracle:thin:@127.0.0.1:1521:orcl";
String USER="root";
String PASSWORD="root";
//1.加载驱动
//mysql
Class.forName("com.mysql.jdbc.Driver");
//oracle
//Class.forName("oracle.jdbc.driver.OracleDriver");
//2.获得数据库链接
Connection conn=DriverManager.getConnection(URL, USER, PASSWORD);
Statement st=conn.createStatement();
//3.执行sql语句
ResultSet rs=st.executeQuery("select username,phone from t_user");
//4.获取返回结果
while(rs.next()){
System.out.println(rs.getString("username")+":"+rs.getString("phone"));
}
//关闭数据资源
rs.close();
st.close();
conn.close();
}catch(Exception e){
e.printStackTrace();
}
}