本文摘自PHP中文网,作者黄舟,侵删。
现在的开发已经很少使用到JDBC了,Mybatis和Hibernate框架已经把JDBC完美的封装,并映射到实体类,我们只需要一个简单的调用就可以完成很多工作,特别是Mybatis,灵活多变。但是,作为一个专业的开发者,JDBC是我们必须深刻理解的,这样才能更好的使用ORM框架。
1.我们连接在使用Java连接数据库的时候,不管是Oracle数据库还是Mysql数据库,都需要一个对应的jar包,Oracle数据库需要的是ojdbc15.jar包,而Mysql数据库需要的是mysql-connector-java-5.1.7-bin.jar包,这两种在网上都可以很方便的找到。
2、Java连接Mysql的代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 | private static String url = "jdbc:mysql://localhost:3306/test" ;
private static String userName = "root" ;
private static String password = "root" ;
public static void main(String[] args) {
MysqlConnectTest mysql= new MysqlConnectTest();
Connection con = mysql.getConnection();
if (con== null ){
System.out.println( "与mysql数据库连接失败!" );
} else {
System.out.println( "与mysql数据库连接成功!" );
}
}
|
3、MysqlConnectTest 类中getConnection()方法如下:
1 2 3 4 5 6 7 8 9 10 11 12 | public Connection getConnection(){
Connection con = null ;
try {
Class.forName( "com.mysql.jdbc.Driver" );
con = DriverManager.getConnection(url, userName, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
|

4、Mysql执行查看语句:
1 2 3 4 5 6 7 8 9 10 11 12 13 | Statement sts = null ;
String sql = "select * from user_table " ;
ResultSet resul = null ;
try {
sts = (Statement) con.createStatement();
resul = sts.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
System. out .println( "查询的结果如下:" );
while(resul. next ()){
System. out .println( "user_id: " +resul.getString( "user_id" )+ ",user_name: " +resul.getString( "user_name" )+ ",user_sex: " +resul.getString( "user_sex" ));
}
|


5、现在执行插入语句,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | String sql = "insert into user_table values ('3','thiscode','1','28','13351210773')" ;
int i = 0;
try {
sts = (Statement) con.createStatement();
i = sts.executeUpdate(sql);
if(i == -1){
System. out .println( "插入失??" );
} else {
System. out .println( "插入成功" );
}
} catch (SQLException e) {
e.printStackTrace();
}
|


说明
Statement和PreparedStatement
以上就是Java如何连接Mysql数据库?的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
如何在mysql数据库中创建新表
数据库的数据抽象有几个级别
mysql新特性归档介绍
mysql怎么查询日期中的月份
mysql的case方法使用好处是什么
mysql为什么不让删外键?
oracle数据库基本语句
mysql的3种分表方案
mysql字段类型有哪些
关于mysql的基础知识详解
更多相关阅读请进入《mysql》频道 >>
机械工业出版社
本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。
转载请注明出处:木庄网络博客 » Java如何连接Mysql数据库?