首先确保你的mysql能够运行,在mysql上创建一个数据库,随便创建一张表,然后添加几个数据。
在项目中引入mysql-jdbc-bin.jar,ojdbc14.jar,可到http://download.csdn.net/source/400716#acomment下载
接下来就是java连接数据库的时候了
以下是源代码:
package com.plague.sql;
import java.io.Reader;
import java.sql.*;
/**
* 1.引包:
* mysql-jdbc-bin.jar,ojdbc14.jar,可到http://download.csdn.net/source/400716#acomment下载
* @author Administrator
*
*/
public class SqlServer {
public static void main(String[] args) {
ResultSet rs = null;
PreparedStatement ps = null;
Connection ct = null;
try{
//加载数据库驱动
try {
Class.forName("org.gjt.mm.mysql.Driver");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//得到连接
try {
ct = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","plague");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//创建preparestatement
ps = ct.prepareStatement("select name,age,sex from user ");
//执行
rs = ps.executeQuery();
//循环取出
while(rs.next()){
String name = rs.getString(1);
int age = rs.getInt(2);
String sex = rs.getString(3);
System.out.println("name: "+name+" age: "+age+" sex: "+sex);
}
}catch (Exception e) {
// TODO: handle exception
}finally{
//关闭数据源
try {
rs.close();
ps.close();
ct.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}