问答文章1 问答文章501 问答文章1001 问答文章1501 问答文章2001 问答文章2501 问答文章3001 问答文章3501 问答文章4001 问答文章4501 问答文章5001 问答文章5501 问答文章6001 问答文章6501 问答文章7001 问答文章7501 问答文章8001 问答文章8501 问答文章9001 问答文章9501

如何设置MYSQL连接JAVA的驱动mysql-connector-java-5.1.10.zip

发布网友 发布时间:2022-04-08 19:38

我来回答

5个回答

懂视网 时间:2022-04-09 00:00

 

一般获取数据库连接的程序

Class.forName("com.mysql.jdbc.Driver");
final Connection connection = (Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/testDB","guoxiaoming","guoxiaoming");

-----------------------------

注册mysql驱动类下次再说,目前重点介绍Connection的建立

-----------------------------

public interface Connection extends Wrapper {

JDK的Connection提供了一种标准,与特定数据库的连接(会话)。在连接上下文中执行 SQL 语句并返回结果。

该Connection接口被数据库驱动类实现,保存有数据库连接中的IO类。

JDBC当中的DriverManager类封装了获取Connection对象的统一方法

public static Connection getConnection(String url, String user, String password) throws SQLException {
 java.util.Properties info = new java.util.Properties();

 // Gets the classloader of the code that called this method, may 
	// be null.
	ClassLoader callerCL = DriverManager.getCallerClassLoader();

	if (user != null) {
	 info.put("user", user);
	}
	if (password != null) {
	 info.put("password", password);
	}

 return (getConnection(url, info, callerCL));
}

 

进入getConnection(url,info,callerCL)方法查看可以看到,

Connection result = di.driver.connect(url, info);

代码最终获取了Connection对象

对应的driver驱动类实现,在jdbc当中

public class NonRegisteringReplicationDriver extends NonRegisteringDriver {
	public NonRegisteringReplicationDriver() throws SQLException {
		super();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.sql.Driver#connect(java.lang.String, java.util.Properties)
	 */
	public Connection connect(String url, Properties info) throws SQLException {
		return connectReplicationConnection(url, info);
	}
}

看到connectReplicationConnection(url,info)方法在父类NonRegisteringDriver类当中

return new ReplicationConnection(masterProps, slavesProps);

看到该类

public ReplicationConnection(Properties masterProperties,
			Properties slaveProperties) throws SQLException {
		this.driver = new NonRegisteringDriver();
		this.slaveProperties = slaveProperties;
		this.masterProperties = masterProperties;

 this.initializeMasterConnection();
 this.initializeSlaveConnection();
 
		this.currentConnection = this.masterConnection;
	}

初始化了两个链接,一个是masterConnection 一个是slaveConnection

看注释

/**
 * Connection that opens two connections, one two a replication master, and
 * another to one or more slaves, and decides to use master when the connection
 * is not read-only, and use slave(s) when the connection is read-only.
 * 
 * @version $Id: ReplicationConnection.java,v 1.1.2.1 2005/05/13 18:58:38
 *  mmatthews Exp $
 */

我们最终看到在ConnectionImpl类当中

protected static Connection getInstance(String hostToConnectTo,
			int portToConnectTo, Properties info, String databaseToConnectTo,
			String url) throws SQLException {
		if (!Util.isJdbc4()) {
			return new ConnectionImpl(hostToConnectTo, portToConnectTo, info,
					databaseToConnectTo, url);
		}

		return (Connection) Util.handleNewInstance(JDBC_4_CONNECTION_CTOR,
				new Object[] {
							hostToConnectTo, Integer.valueOf(portToConnectTo), info,
							databaseToConnectTo, url }, null);
	}

  实例化了该类的一个子类

public class JDBC4Connection extends ConnectionImpl 

 通过构造方法

public JDBC4Connection(String hostToConnectTo, int portToConnectTo, Properties info, String databaseToConnectTo, String url) throws SQLException {
	super(hostToConnectTo, portToConnectTo, info, databaseToConnectTo, url);
	// TODO Auto-generated constructor stub
}

在其父类中

protected ConnectionImpl(String hostToConnectTo, int portToConnectTo, Properties info,
			String databaseToConnectTo, String url)
			throws SQLException {
	
		this.connectionCreationTimeMillis = System.currentTimeMillis();
		
		if (databaseToConnectTo == null) {
			databaseToConnectTo = "";
		}

重点关于方法

public void createNewIO(boolean isForReconnect)
			throws SQLException {
		synchronized (getConnectionMutex()) {
			// Synchronization Not needed for *new* connections, but defintely for
			// connections going through fail-over, since we might get the
			// new connection up and running *enough* to start sending
			// cached or still-open server-side prepared statements over
			// to the backend before we get a chance to re-prepare them...
			
	
			Properties mergedProps = exposeAsProperties(this.props);
	
			if (!getHighAvailability()) {
				connectOneTryOnly(isForReconnect, mergedProps);
				
				return;
			} 
	
			connectWithRetries(isForReconnect, mergedProps);
		}		
	}

 

最终我们看到在coreConnect方法中实现了具体的链接

private void coreConnect(Properties mergedProps) throws SQLException,
			IOException {
		int newPort = 3306;
		String newHost = "localhost";
		
		String protocol = mergedProps.getProperty(NonRegisteringDriver.PROTOCOL_PROPERTY_KEY);
		
		if (protocol != null) {
			// "new" style URL

			if ("tcp".equalsIgnoreCase(protocol)) {
				newHost = normalizeHost(mergedProps.getProperty(NonRegisteringDriver.HOST_PROPERTY_KEY));
				newPort = parsePortNumber(mergedProps.getProperty(NonRegisteringDriver.PORT_PROPERTY_KEY, "3306"));
			} else if ("pipe".equalsIgnoreCase(protocol)) {
				setSocketFactoryClassName(NamedPipeSocketFactory.class.getName());
				
				String path = mergedProps.getProperty(NonRegisteringDriver.PATH_PROPERTY_KEY);
				
				if (path != null) {
					mergedProps.setProperty(NamedPipeSocketFactory.NAMED_PIPE_PROP_NAME, path);
				}
			} else {
				// normalize for all unknown protocols
				newHost = normalizeHost(mergedProps.getProperty(NonRegisteringDriver.HOST_PROPERTY_KEY));
				newPort = parsePortNumber(mergedProps.getProperty(NonRegisteringDriver.PORT_PROPERTY_KEY, "3306"));
			}
		} else {
		
			String[] parsedHostPortPair = NonRegisteringDriver
					.parseHostPortPair(this.hostPortPair);
			newHost = parsedHostPortPair[NonRegisteringDriver.HOST_NAME_INDEX];

			newHost = normalizeHost(newHost);

			if (parsedHostPortPair[NonRegisteringDriver.PORT_NUMBER_INDEX] != null) {
				newPort = parsePortNumber(parsedHostPortPair[NonRegisteringDriver.PORT_NUMBER_INDEX]);
			}
		}

		this.port = newPort;
		this.host = newHost;
		
		this.io = new MysqlIO(newHost, newPort,
				mergedProps, getSocketFactoryClassName(),
				getProxy(), getSocketTimeout(),
				this.largeRowSizeThreshold.getValueAsInt());
		this.io.doHandshake(this.user, this.password,
				this.database);
	}

 

在new MysqlIO类当中的构造方法中实现

 public MysqlIO(String host, int port, Properties props,
 String socketFactoryClassName, MySQLConnection conn,
 int socketTimeout, int useBufferRowSizeThreshold) throws IOException, SQLException {
 this.connection = conn;
 
 if (this.connection.getEnablePacketDebug()) {
  this.packetDebugRingBuffer = new LinkedList<StringBuffer>();
 }
 this.traceProtocol = this.connection.getTraceProtocol();
 

 this.useAutoSlowLog = this.connection.getAutoSlowLog();
 
 this.useBufferRowSizeThreshold = useBufferRowSizeThreshold;
 this.useDirectRowUnpack = this.connection.getUseDirectRowUnpack();

 this.logSlowQueries = this.connection.getLogSlowQueries();

 this.reusablePacket = new Buffer(INITIAL_PACKET_SIZE);
 this.sendPacket = new Buffer(INITIAL_PACKET_SIZE);

 this.port = port;
 this.host = host;

 this.socketFactoryClassName = socketFactoryClassName;
 this.socketFactory = createSocketFactory();
 this.exceptionInterceptor = this.connection.getExceptionInterceptor();
 
 try {
 	this.mysqlConnection = this.socketFactory.connect(this.host,
 		this.port, props);
	 
	
	 if (socketTimeout != 0) {
	 	try {
	 		this.mysqlConnection.setSoTimeout(socketTimeout);
	 	} catch (Exception ex) {
	 		/* Ignore if the platform does not support it */
	 	}
	 }
	
	 this.mysqlConnection = this.socketFactory.beforeHandshake();
	
	 if (this.connection.getUseReadAheadInput()) {
	 	this.mysqlInput = new ReadAheadInputStream(this.mysqlConnection.getInputStream(), 16384,
	 			this.connection.getTraceProtocol(),
	 			this.connection.getLog());
	 } else if (this.connection.useUnbufferedInput()) {
	 	this.mysqlInput = this.mysqlConnection.getInputStream();
	 } else {
	 	this.mysqlInput = new BufferedInputStream(this.mysqlConnection.getInputStream(),
	 			16384);
	 }
	
	 this.mysqlOutput = new BufferedOutputStream(this.mysqlConnection.getOutputStream(),
	 		16384);
	
	
	 this.isInteractiveClient = this.connection.getInteractiveClient();
	 this.profileSql = this.connection.getProfileSql();
	 this.autoGenerateTestcaseScript = this.connection.getAutoGenerateTestcaseScript();
	
	 this.needToGrabQueryFromPacket = (this.profileSql ||
	 		this.logSlowQueries ||
	 		this.autoGenerateTestcaseScript);
	
	 if (this.connection.getUseNanosForElapsedTime()
					&& Util.nanoTimeAvailable()) {
				this.useNanosForElapsedTime = true;
	
				this.queryTimingUnits = Messages.getString("Nanoseconds");
			} else {
				this.queryTimingUnits = Messages.getString("Milliseconds");
			}
	
			if (this.connection.getLogSlowQueries()) {
				calculateSlowQueryThreshold();
			}
 } catch (IOException ioEx) {
 	throw SQLError.createCommunicationsException(this.connection, 0, 0, ioEx, getExceptionInterceptor());
 }
 }

 

this.mysqlConnection = this.socketFactory.connect(this.host,this.port, props);
这样就返回了Socket对象

在StandardSocketFactory类当中
if (this.host != null) {
				if (!(wantsLocalBind || wantsTimeout || needsConfigurationBeforeConnect)) {
					InetAddress[] possibleAddresses = InetAddress
							.getAllByName(this.host);

					Throwable caughtWhileConnecting = null;

					// Need to loop through all possible addresses, in case
					// someone has IPV6 configured (SuSE, for example...)

					for (int i = 0; i < possibleAddresses.length; i++) {
						try {
							this.rawSocket = new Socket(possibleAddresses[i],
									port);

							configureSocket(this.rawSocket, props);

							break;
						} catch (Exception ex) {
							caughtWhileConnecting = ex;
						}
					}

					if (rawSocket == null) {
						unwrapExceptionToProperClassAndThrowIt(caughtWhileConnecting);
					}
				} else {
					// must explicitly state this due to classloader issues
					// when running on older JVMs :(
					try {

						InetAddress[] possibleAddresses = InetAddress
								.getAllByName(this.host);

						Throwable caughtWhileConnecting = null;

						Object localSockAddr = null;

						Class<?> inetSocketAddressClass = null;

						Constructor<?> addrConstructor = null;

						try {
							inetSocketAddressClass = Class
									.forName("java.net.InetSocketAddress");

							addrConstructor = inetSocketAddressClass
									.getConstructor(new Class[] {
											InetAddress.class, Integer.TYPE });

							if (wantsLocalBind) {
								localSockAddr = addrConstructor
										.newInstance(new Object[] {
												InetAddress
														.getByName(localSocketHostname),
												new Integer(0 /*
																 * use ephemeral
																 * port
																 */) });

							}
						} catch (Throwable ex) {
							unwrapExceptionToProperClassAndThrowIt(ex);
						}

						// Need to loop through all possible addresses, in case
						// someone has IPV6 configured (SuSE, for example...)

						for (int i = 0; i < possibleAddresses.length; i++) {

							try {
								this.rawSocket = new Socket();

								configureSocket(this.rawSocket, props);

								Object sockAddr = addrConstructor
										.newInstance(new Object[] {
												possibleAddresses[i],
												Integer.valueOf(port) });
								// bind to the local port if not using the ephemeral port
								if (localSockAddr != null) {
									socketBindMethod.invoke(rawSocket,
											new Object[] { localSockAddr });
								}

								connectWithTimeoutMethod.invoke(rawSocket,
										new Object[] { sockAddr,
												Integer.valueOf(connectTimeout) });

								break;
							} catch (Exception ex) {	
								this.rawSocket = null;

								caughtWhileConnecting = ex;
							}
						}

						if (this.rawSocket == null) {
							unwrapExceptionToProperClassAndThrowIt(caughtWhileConnecting);
						}

					} catch (Throwable t) {
						unwrapExceptionToProperClassAndThrowIt(t);
					}
				}

				return this.rawSocket;
			}

针对host可能对应多个ip的可能性,连接到其中一个ip之后就break退出

MySQL驱动阅读------Connection连接的建立,基于JDBC-----5.1.26

标签:

热心网友 时间:2022-04-08 21:08

classpath=.;C:\Program Files\Java\jdk1.6.0_10\lib\dt.jar;C:\Program Files\Java\jdk1.6.0_10\lib\tools.jar;D:\tomcat-6.0.32\lib\servlet-api.jar;mysql-connector-java-5.0.4-bin.jar
- - - - - - - - -
JAVA_HOME=C:\Program Files\Java\jdk1.6.0_10
- - - - - - - - -
Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\ProgramFiles\Common Files\Thunder Network\KanKan\Codecs;C:\Program Files\Yuguo;C:\Program Files\Java\jdk1.6.0_10\bin;C:\Program Files\Microsoft SQL Server\80\Tools\BINN;E:\MySQL\MySQL Server 5.5\bin;D:\android-sdk\tools;E:\MySQL\MySQLServer5.0\bin;E:\MinGW32\bin
- - - - - - - - -
我的配置如上,对比下看关于java和mysql的配置缺什么。另外,WEB工程中,将mysql连接包放在lib文件夹下。注意下 mysql的连接用户密码及工程中的对应。
- - - - - - - - -
应该 看下控制台的报错原因。

热心网友 时间:2022-04-08 22:26

是不是你的代码问题啊,你对照下代码,前提是你已经把mysql的jar包已经放在你的工程里了
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://127.0.0.1:3306/这里写数据库名称";
// 加载驱动程序
Class.forName(driver);
// 连续数据库
Connection conn = DriverManager.getConnection(url,这里写用户名, 密码);

热心网友 时间:2022-04-09 00:00

把你连接mysql那段代码发出来看看

热心网友 时间:2022-04-09 01:52

有没有安装驱动啊,java数据库的驱动
声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com
畅享好还是荣耀好 怎么向老师请教问题?? ...和是40.15较大数的小数点向左移动一位就等于较小的数,这两_百度知... 两个数的和是40.15,较大数的小数点向左移动一位就等于较小的数这两... 两个数的和是40.15,较大的数的小数点像向左移动一位就等于较小的数... 两个数的和是40.15,较大数的小数点向左移动一位等于较小的数 ...和是40.15较大数的小数点向左移动一位就等于较小的数这两个数分别... 怎么用手机查询农行信用卡余额? 朝阳公园附近有孩子可以托管的地方吗? 华泰证券怎么添加第二张银行卡 治疗风湿病用姜水泡脚有用吗? 经常泡脚会有风湿吗? 每天泡脚会得风湿吗? 风湿关节炎经常用热水泡脚有好处吗,大腿和小腿后方的 风湿性关节炎每天热水泡脚有好处吗 经常用热水泡脚,可以对很多疾病起到辅助的治疗吗? 请问!风湿病可以泡脚吗? 泡脚可以治疗风湿吗? 花椒泡脚治风湿吗? 泡脚对风湿作用明显吗? 隶书书法字体杜牧诗清明时节雨纷纷这首诗的写法 求闻之若此是定语后置吗 龟字隶书写法 泡脚对风湿有什么好处 得了风湿经常泡脚好吗 诺基亚N78手机进水 开不了机怎么解决 iphone 12开关机方法 诺基亚2700C手机进水后漏电100MA开不了机怎么修 诺基亚n8进水了 换了电脑 旧电脑里硬盘里的360极速浏览器网址收藏夹里的网址怎么找到? 食盐泡脚对风湿病有好处吗? 求闻之若此是什么特殊句式 穿井得一人文言文词类活用? 穿井得一人实词虚词翻译 circle女装 有养殖的龙虾的朋友你们好,在这里和大家说一件事情,淘宝上以低价格卖龙虾的,都是骗人的,他们以低价格 现在虾苗多少钱一斤? CIRCLE怎么样 淘宝上买了虾苗用输中死亡卖家需要负责任吗 淘宝快递龙纹虾苗用充氧气吗? circleplex-2怎么样 蓝魔观赏虾怎么养殖,在长春有卖的吗? circle女装上海的地址 文言文穿井得人中“求闻之若此,不若无闻也”的翻译 大家谁知道什么样的观赏虾蓝月是最好的 顶峰虾苗怎么样好吗是高抗苗吗? 穿井得人 观赏虾缸里的微生物培养 快看漫画中一本男扮女装的耽美小说漫画,是英文名。 养鳌虾用什么过滤器,裸缸可以吗?