import java.sql.*;
public class Ch09 {
private static Connection getConnection()throws SQLException{
Connection conn=null;
conn=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8",
"root","123456");
return conn;
}
public static void queryDemo1(){
String sql="select * from customers";
System.out.println("SQL:"+sql);
Connection conn=null;
Statement st=null;
ResultSet rs=null;
try{
conn=getConnection();
st=conn.createStatement();
rs=st.executeQuery(sql);
while(rs.next()){
System.out.println("ID:"+rs.getInt("ID"));
System.out.println("Name:"+rs.getString("Name"));
System.out.println("Age:"+rs.getInt("age"));
System.out.println("Phone:"+rs.getString("Phone"));
System.out.println("===============================/n");
}
}
catch(SQLException e)
{
System.out.println("Exception:"+e.getMessage());
}
finally{
try{
if(rs!=null){
rs.close();
}
if(st!=null){
st.close();
}
if(conn!=null){
conn.close();
}
}catch(Exception e)
{
}
}
}
public static void queryDemo2(int age){
String sql="select * from customers where Age>"+age;
Connection conn=null;
PreparedStatement pst=null;
ResultSet rs=null;
try{
conn=getConnection();
pst=conn.prepareStatement(sql);
pst.setInt(1,20);
rs=pst.executeQuery();
while(rs.next()){
System.out.println("ID:"+rs.getInt("ID"));
System.out.println("Name:"+rs.getString("Name"));
System.out.println("Age:"+rs.getInt("age"));
System.out.println("Phone:"+rs.getString("Phone"));
System.out.println("===============================/n");
}
}
catch(SQLException e)
{
System.out.println("Exception:"+e.getMessage());
}
finally{
try{
if(rs!=null){
rs.close();
}
if(pst!=null){
pst.close();
}
if(conn!=null){
conn.close();
}
}catch(Exception e)
{
}
}
}
public static void modifyDemo(){
String insertSQL="insert into Customers(Name,Age,Phone) values('贾',22,'13123423444')";
String updateSQL="update Customers set Name='Test02' where ID=4";
String deleteSQL="delete from Customers where ID=4";
Connection conn=null;
Statement st=null;
try{
conn=getConnection();
st=conn.createStatement();
int affectRec=st.executeUpdate(insertSQL);
if(affectRec>0){
System.out.println(affectRec+" Record modifed. ");
}
}
catch(SQLException e)
{
System.out.println("Exception:"+e.getMessage());
}
finally{
try{
if(st!=null){
st.close();
}
if(conn!=null){
conn.close();
}
}catch(Exception e)
{
}
}
}
public static void main(String[] args) {
System.out.println("DataBase Operation Demo");
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException e)
{
System.out.println("Driver Class:com.mysql.jdbc.Driver not found.");
}
//modifyDemo();
queryDemo1();
//queryDemo2(21);
}
}
连接MySQL数据库
最新推荐文章于 2023-03-28 20:37:30 发布