java连接oracle或者mysql

由于经常忘记怎么连接oracle或者mysql ,所以记录一下

/* 先引入jar包:orcle包类似ojdbc14.jar
				mysql包类似mysql-connector-java-5.1.10
			本地装orcle的话,可以在安装目录的 E:\oracle\product\10.2.0\db_1\jdbc\lib
			 如果没有的话,以上的包都可以在maven中央仓库或者对应的官网上找得到
mysql: 
    
	 driver :com.mysql.jdbc.Driver;
	 url : jdbc:mysql://localhost:3306/bojoydb
	 
orcle :  driver :oracle.jdbc.OracleDriver
         url: jdbc:oracle:thin:@192.168.x.xxx:1521:dbname
   连接步骤:
     1.注册驱动
	 2.DriverManager获取connection对象
	 3.connection对象查询得到ResultSet
	 4,遍历结果集ResultSet
	 5.关闭连接
     以下是最简单的连接方式,一般的话,数据库的配置放在properties里面,对应的获取Connection 也都
     是封装成相应的工具类,然后通过类去调用	 
*/
package test;

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

public class TestOracle {
	public static void main(String[] args) throws SQLException {
		 String userName = "root";
	     String password = "123456";
	     String driver = "oracle.jdbc.OracleDriver";
	     String url = "jdbc:oracle:thin:@192.168.1.123:1521:testdb";
	     Connection connection =null;
	     Statement createStatement= null;
	     ResultSet executeQuery =null;
		try{
			
			Class.forName(driver);
			
			connection = DriverManager.getConnection(url,userName,password);
			
			String str = "select count(*) as te  from t_user ";
			
			createStatement = connection.createStatement();
			
			
			 executeQuery = createStatement.executeQuery(str);
			while(executeQuery.next()){
				String string = executeQuery.getString("te");
				System.out.println("总数:"+string);
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally {
			
			if (executeQuery!=null) executeQuery.close();
			if (createStatement!=null) createStatement.close();
			if (connection!=null) connection.close();
		}
		
	}

}

猜你喜欢

转载自blog.csdn.net/try_and_do/article/details/81207974