1、加载驱动 Class.forName(“驱动”);
2、连接数据库 Connection con = DriverManager.getConnection(url , username , password ) ;
3、创建一个Statement Statement stmt = con.createStatement() ; 或者PreparedStatement pstmt = con.prepareStatement(sql) ;
4、执行SQL语句 ResultSet rs = stmt.ececuteQuery("select * from ......");
5、处理结果 while(rs.next()){ String name = rs.getString("name"); 或者 String name = rs.getString(1); }
6、关闭jdbc对象 rs.close(); stmt.close(); con.close();
示例:
连接oracle数据库
public class ConnOracle {
String user = "system";
String psaaword ="12345";
if(rs != null){ rs.close(); }
if(stmt != null){ stmt.close(); }
if(con != null){ con.close(); }
连接mySql数据库
public class ConnMySQL {
ResultSet rs= null;
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","user","password"); //jdbc:mysql://host:port/database
pre.setString(1,"zhangsan");
rs=pre.executeQuery();
if(rs != null){ rs.close(); }
if(stmt != null){ stmt.close(); }
if(con != null){ con.close(); }
} 连接SqlServer数据库
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
Connection con = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=test","user","password");
将驱动、url、userName、password替换即可