Java连接mysql数据库
2015-07-24 10:21
489 查看
1.先创建一个Java项目testMysql(我使用的是intellij编辑器)。
2.导入mysql的驱动包。
(1)
(2)
(4)
3.编写代码
2.导入mysql的驱动包。
(1)
(2)
(4)
3.编写代码
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * Created by wuy on 2015/7/24. */ public class testMysql { private Connection con; private String user="root"; private String password="root"; private String className="com.mysql.jdbc.Driver"; private String url = "jdbc:mysql://127.0.0.1:3306/goods"; public testMysql(){ try{ Class.forName(className); System.out.println("加载数据库驱动成功!"); }catch(ClassNotFoundException e){ System.out.println("加载数据库驱动失败!"); e.printStackTrace(); } } /**创建数据库连接*/ public Connection getCon(){ try { con= DriverManager.getConnection(url, user, password); System.out.println("创建数据库连接成功!"); } catch (SQLException e) { System.out.print(con); System.out.println("创建数据库连接失败!"); con=null; e.printStackTrace(); } return con; } public void closed(){ try{ if(con!=null){ con.close(); } }catch(SQLException e){ System.out.println("关闭con对象失败!"); e.printStackTrace(); } } public static void main(String[] args) { testMysql c=new testMysql(); c.getCon(); c.closed(); } } 4.运行结果截图
相关文章推荐
- Java IO学习【5】复制一个文本文件
- java并发编程实战第五章(3)异步运行任务
- Spring+iBatis+Atomikos实现JTA事务
- java中全排列的生成算法汇总
- svn切换用户名-密码
- Java中InputStream和OutputStream的区别
- java正则表达式之捕获分组与Back引用
- spring mvc 自定义拦截器
- eclipse中奇怪的是乱码
- spring 定时器
- java虚拟机_jvm_java内存区域
- myeclipse发布项目很慢。
- Eclipse搭建SSH(Struts2+Spring3+Hibernate3)框架项目教程
- java.lang.NoClassDefFoundError: ActionSupport异常和Action class not found异常
- java虚拟机_jvm(1)
- Java 动态代理机制分析及扩展,第 1 部分
- 在eclipse上以link方式安装CDT插件
- JAVA—Day01
- Spring -- spEL&Bean的生命周期&工厂方法配置Bean
- Java中获得数据库连接的几种方法