Eclipse中连接MySQL数据库

MySQL下载地址:http://dev.mysql.com/downloads/mysql/

MySQL的JDBC驱动下载地址:http://dev.mysql.com/downloads/connector/j/

第一步:配置环境

解压下载的MySQL JDBC驱动的压缩文件,将其中的mysql-connector-java-5.1.18-bin.jar复制到Java Web项目的WEB-INF/lib目录下。

打开MySQL,连接要测试的数据库test

第二步:加载JDBC驱动程序

有两种方法:

(1)利用System类的静态方法setProperty(),例如加载JDBC驱动,方法如下:

System.setProperty("jdbc.drivers","com.mysql.jdbc.Driver");

(2)利用Class类的类方法forName(),例如加载JDBC驱动,方法如下:

Class.forName("com.mysql.jdbc.Driver");

第三步:建立与数据库的连接

Connection con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/test?user=root&password=passwd");

或者

Connection con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/test",root,passwd);


源代码:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"
    import="java.sql.*"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>数据库连接测试</title>
</head>
<body>
<%
Connection con=null;
String url="jdbc:mysql://localhost:3306/test";


try{
out.print("加载驱动....");
Class.forName("com.mysql.jdbc.Driver");
out.print("加载驱动成功");
}catch(Exception e)
{
out.print("加载驱动失败");
}
out.print("<br>");
try{
out.print("连接数据库....");
con=DriverManager.getConnection(url,"root","123456");
out.print("连接数据库成功");
}catch(Exception e)
{
out.print("连接失败");
}
con.close();
%>
</body>
</html>


结果如下:

加载驱动....加载驱动成功
连接数据库....连接数据库成功


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值