初试数据库--eclipse连接数据库mysql,非常简单的入门!

最新学习所得

eclipse平台中连接数据库,没想到这么简单!总共分几步:

1. 下载mysql-connector-java-5.1.8.jar,并加到eclipse工程中;

2. 用吧!用得过程分几步:

  1. connection:可完成用户名,密码,数据库的连接,可创建statement来实现sql操作,
  2. statement:可执行sql语句,
  3. resultset:对statement执行sql后,返回的记录进行处理,其类下有rs.getString(),getFloat()等等函数;使用结束后,三者都要close()

具体示例如下所示:


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DBtest {
public static void main(String agrs[]) {
String driver = "com.mysql.jdbc.Driver";
try {
Connection con;
Statement stmt;
ResultSet rs;

Class.forName(driver);
DriverManager.registerDriver(new com.mysql.jdbc.Driver());

String dbUrl = "jdbc:mysql://localhost:3306/bookdb?useUnicode=true&characterEncoding=gb2312";
String user = "root";
String password = "";
con = DriverManager.getConnection(dbUrl, user, password);
//与数据库建立连接

stmt = con.createStatement();
String sql = "select id,name,title,price from books";
stmt.executeUpdate("insert into books (id,name,title,price) values ('123','tom','tomcat bible',44.5)");
rs = stmt.executeQuery(sql);

//con 創建stmt,stmt执行sql语句,将查询结果返回给rs,由循环处理rs获得的字段
while (rs.next()) {
String col1 = rs.getString("id");
String col2 = rs.getString("name");
String col3 = rs.getString("title");
float col4 = rs.getFloat("price");
System.out.println(col1+"\t"+col2+"\t"+col3+"\t"+col4);
}

stmt.executeUpdate("delete from books where id = '123'");
//stmt执行sql语句

rs.close();//关闭rs,con,stmt
stmt.close();
con.close();

} catch (Exception e) {
System.out.println("无法加载驱动程序" + driver);
}
}

}

你可能感兴趣的:(eclipse,sql,数据库,mysql,String,books)