您的位置:首页 > 编程语言 > Java开发

java 学习之连接 mysql

2014-06-19 21:41 357 查看
首先要将mysql-connector-java-5.1.10-bin.ja加入系统java工程文件中

下载地址http://download.csdn.net/detail/u014112584/7359185

Mysql----->右击选择Properties属性--------------->Add External JARS



测试例子

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;

public class MysqlTest {

static String drivername="com.mysql.jdbc.Driver";
static String url="jdbc:mysql://localhost:3306/expression";//指向数据源
static String username="root";
static String password="";
static java.sql.Statement stmt=null;
static ResultSet re=null;
static Connection conn=null;
static PreparedStatement pstm=null;
/*
* 构造函数进行初始化
*/
public MysqlTest(){
try{
Class.forName(drivername);//将驱动加载到运行环境中,加载的时候,驱动会自动向DriverManager完成注册
System.out.println("创建驱动成功");
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
/*
* 获取连接
*/
public static Connection getConnection(){
conn=null;
try{
conn=(Connection)DriverManager.getConnection(url, username, password);//有了驱动和连接地址后,需要使用DriverManager来获取连接
System.out.println("连接数据库成功!");
}catch(SQLException e){
e.printStackTrace();
}
return conn;
}
/**
* 关闭连接
* @param args
*/
public static void free(ResultSet rs,Connection conn,java.sql.Statement stmt2){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("关闭ResultSet失败!");
e.printStackTrace();
}finally{
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("关闭Connection失败!");
e.printStackTrace();
}finally{
if(stmt2!=null){
try {
stmt2.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("关闭Statement失败!");
e.printStackTrace();
}
}
}
}
}
}
}
public static void main(String[]args){

MysqlTest.getConnection();
try {
stmt=conn.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
re=stmt.executeQuery("select * from data");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int i=1;
try {
while(re.next()){
System.out.println(i++);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
free(re,conn,stmt);
System.out.println("OK");
}
}


更多java连接数据库
http://download.csdn.net/detail/u014112584/7359179
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java mysql 数据库