学习笔记,如有错误,还望不吝赐教!
参考网页:http://www.cnblogs.com/magicianCoder/p/5506589.html
第一步:下载mysql-conerctor-java-xxx-bin.jar,并且引入到Referenced Libraries中。
第二步:写连接方式代码:
package jdbc;
import java.sql.Connection;
public class Values
{
public static String DRIVER_MYSQL = "com.mysql.jdbc.Driver";
public static String URL = "jdbc:mysql://localhost:3306/Student?"
+ "user=root&password=0301&useUnicode=true&characterEncoding=UTF8";
}
然后加载,连接,查询数据库,获得数据:
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestJDBC
{
private Statement statement;
public TestJDBC() {
try
{
Class.forName(Values.DRIVER_MYSQL); //加载JDBC驱动
System.out.println("Driver Load Success.");
Connection connection = DriverManager.getConnection(Values.URL); //创建数据库连接对象
statement = connection.createStatement(); //创建Statement对象
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* 根据sql查询数据库,返回一个结果集
* 输 入:SQL语句
* 返回值:ResultSet 查询结果
*/
public ResultSet query(String sql) {
ResultSet result = null;
try
{
result = statement.executeQuery(sql);
} catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
/*
* 打印UserInfo表的数据
* 输 入:结果集(数据表)
* 返回值:空
*/
public void printUserInfo(ResultSet result) {
try
{
while(result.next()) {
System.out.println("userNname:" + result.getString(1)
+ ", password:" + result.getString(2));
}
} catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* 执行数据操作
* 输 入:SQL语句
* 返回值:空
*/
public void executeSql(String sql) {
try
{
statement.execute(sql);
} catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
String sql = "SELECT * FROM info";
TestJDBC db = new TestJDBC();
ResultSet result = db.query(sql);
db.printUserInfo(result);
}
}