java调取数据库

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
* Created by liwenj on 2017/8/7.
*/
public class T1 {
public static void main(String[] args) throws Exception {
//取得jdbc的驱动包
Class.forName("com.mysql.jdbc.Driver");
//取得数据库
String url="jdbc:mysql://localhost:3306/test";
String user="root";
String password="123";
Connection connection=DriverManager.getConnection(url,user,password);
Statement statement = connection.createStatement();
//增加表格
String sql="INSERT INTO user1(NO,NAME,age,sex) VALUES('001','小明',22,'男')";
int i=statement.executeUpdate(sql);
System.out.println(i);
//更改表格
String upsql="UPDATE user1 SET sex='女',age=21 WHERE NO='003'";
statement.executeUpdate(upsql);
//删除表格
String delsql="DELETE FROM user1 WHERE NO='001'";
statement.executeUpdate(delsql);
ResultSet resultSet = statement.executeQuery("SELECT * FROM user1 WHERE NO='002'AND NAME='李四'");
while (resultSet.next()){
String no = resultSet.getString("no");
int age = resultSet.getInt("age");
String sex = resultSet.getString("sex");
System.out.println(no+"---"+age+"---"+sex);
}
resultSet.close();
statement.close();
connection.close();
}
}
异常报错版本
import java.sql.*;

/**
* Created by liwenj on 2017/8/7.
*/
public class T1 {
public static void main(String[] args) {
Connection connection=null;
Statement statement=null;
ResultSet resultSet=null;
try{
//取得jdbc的驱动包
Class.forName("com.mysql.jdbc.Driver");
//取得数据库
String url="jdbc:mysql://localhost:3306/test";
String user="root";
String password="123";
connection=DriverManager.getConnection(url,user,password);
statement = connection.createStatement();
//增加表格
String sql="INSERT INTO user1(NO,NAME,age,sex) VALUES('001','小明',22,'男')";
int i=statement.executeUpdate(sql);
System.out.println(i);
//更改表格
String upsql="UPDATE user1 SET sex='女',age=21 WHERE NO='003'";
statement.executeUpdate(upsql);
//删除表格
String delsql="DELETE FROM user1 WHERE NO='001'";
statement.executeUpdate(delsql);
resultSet = statement.executeQuery("SELECT * FROM user1 WHERE NO='002'AND NAME='李四'");
while (resultSet.next()){
String no = resultSet.getString("no");
int age = resultSet.getInt("age");
String sex = resultSet.getString("sex");
System.out.println(no+"---"+age+"---"+sex);
}
}catch (Exception e){
System.out.println("出错");
e.fillInStackTrace();
}finally {
if (resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

}
}
}
posted @ 2017-08-07 16:13  斯丢皮德曼  阅读(308)  评论(0编辑  收藏  举报