Java中获取myql数据源

1.在tomcat 中配置mysql 数据源

 

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DBUtil {

	/**
	 * 在tomcat的server.xml中配置datasource
	 * 
	 *
	 <Context path="/vote" docBase="D:\tomcat6.0.13\vote\WebRoot"   crossContext="true" reloadable="true" debug="1">
		  <Resource name="jdbc/MySQL" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="root" password="123456" driverClassName="org.gjt.mm.mysql.Driver"
               url="jdbc:mysql://localhost:3306/vote?characterEncoding=UTF-8"/>
		</Context>
	 
	 */
	 private static DataSource ds = null;
	 private Connection conn;
	 
	public Connection getConnection () throws Exception{
		
		try {
			if (ds == null) {
				initDS();
			}
			conn = ds.getConnection();
			conn.setAutoCommit(false);
			return conn ;
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		}
		 
	}
	
	//通过jndi获取ds
	private  void initDS () throws Exception {
		try {
			Context initContext = new InitialContext ();
			Context envContext= (Context) initContext.lookup("java:/comp/env");
			ds = (DataSource) envContext.lookup("jdbc/MySQL");
			//return ds ;
			
		}catch (NamingException e){
			e.printStackTrace();
		}catch (ClassCastException e2){
			e2.printStackTrace();
		}
		
	}
	
}

 

 

2.直接在java中获取数据源

 

 Class.forName("org.git.mm.mysql.Driver"); 

Stringurl=”jdbc:mysql://localhost/myDB?user=soft&password=soft1234&useUnicode=true&characterEncoding=8895_1” 

  Connection con = DriverManager.getConnection(url); 

 

或:

 

 

String url = "jdbc:mysql://localhost:3306/";   

String dbName = "taskproject";   

String driverName = "org.gjt.mm.mysql.Driver";    

String userName = "root";   

String password = "root";   

Class.forName(driverName).newInstance();   

con=DriverManager.getConnection(url+dbName, userName,   password);   

 

 

 

你可能感兴趣的:(java,sql,tomcat,mysql,jdbc)