引入jar包:mysql-connector-java-5.1.39-bin.jar
编写:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BaseDao {
private final String USERNAME="root";
private final String PASSWORD="root";
private final String URL="jdbc:mysql://localhost:3306/news";
private final String DRIVER="com.mysql.jdbc.Driver";
public Connection con=null;
public PreparedStatement ps=null;
public ResultSet rs=null;
public void getConnetion(){
try {
Class.forName(DRIVER);
con=(Connection) DriverManager.getConnection(URL,USERNAME,PASSWORD);
ps= con.prepareStatement("select * from news");
rs=ps.executeQuery();
while(rs.next()){
System.out.println(rs.getString("NewTitle"));
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
close();
}
}
//关闭连接
public void close(){
try {
if(rs!=null)
rs.close();
if(ps!=null)
ps.close();
if(con!=null)
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
测试:
public class test {
/**
* @param args
*/
public static void main(String[] args) {
BaseDao bd=new BaseDao();
bd.getConnetion();
}
}
//Oracle8/8i/9i数据库(thin模式)
String url="jdbc:oracle:thin:@localhost:1521:orcl";
String user="scott";
String password="tiger";
Connection conn=DriverManager.getConnection(url,user,password);
//Sql Server7.0/2000/2005/2008数据库
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs";
String user="sa";
String password="";
Connection conn=DriverManager.getConnection(url,user,password);
//DB2数据库
String url="jdbc:db2://localhost:5000/sample";
String user="amdin"
String password=-"";
Connection conn=DriverManager.getConnection(url,user,password);
//MySQL数据库
String url="jdbc:mysql://localhost:3306/testDB?user=root&password=root&useUnicode=true&characterEncoding=gb2312";
Connection conn=DriverManager.getConnection(url);