日期:2014-05-16 浏览次数:20567 次
JDBC是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用JAVA编写的类和接口组成。说白了就和PHP的PDO一样,通过JDBC,JAVA可以使用相同的API接口来链接例如:MYSQL,SQLSERVER等不同类型的数据库。
package main; import java.sql.Connection; import java.sql.DriverManager; public class Mysql { public static void main(String arg[]) { try { Connection con = null; //定义一个MYSQL链接对象 Class.forName("com.mysql.jdbc.Driver").newInstance(); //MYSQL驱动 con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "root"); //链接本地MYSQL System.out.print("yes"); } catch (Exception e) { System.out.print("MYSQL ERROR:" + e.getMessage()); } } }
package main; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class Mysql { /** * 入口函数 * @param arg */ public static void main(String arg[]) { try { Connection con = null; //定义一个MYSQL链接对象 Class.forName("com.mysql.jdbc.Driver").newInstance(); //MYSQL驱动 con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "root"); //链接本地MYSQL Statement stmt; //创建声明 stmt = con.createStatement(); //新增一条数据 stmt.executeUpdate("INSERT INTO user (username, password) VALUES ('init', '123456')"); ResultSet res = stmt.executeQuery("select LAST_INSERT_ID()"); int ret_id; if (res.next()) { ret_id = res.getInt(1); System.out.print(ret_id); } } catch (Exception e) { System.out.print("MYSQL ERROR:" + e.getMessage()); } } }
package main; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class Mysql { /** * 入口函数 * @param arg */ public static void main(String arg[]) { try { Connection con = null; //定义一个MYSQL链接对象 Class.forName("com.mysql.jdbc.Driver").newInstance(); //MYSQL驱动 con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "root"); //链接本地MYSQL Statement stmt; //创建声明 stmt = con.createStatement(); //新增一条数据 stmt.executeUpdate("INSERT INTO user (username, password) VALUES ('init', '123456')"); ResultSet res = stmt.executeQuery("select LAST_INSERT_ID()"); int ret_id; if (res.next()) { ret_id = res.getInt(1); System.out.print(ret_id); } //删除一条数据 String sql = "DELETE FROM user WHERE id = 1"; long deleteRes = stmt.executeUpdate(sql); //如果为0则没有进行删除操作,如果大于0,则记录删除的条数 System.out.print("DELETE:" + deleteRes); //更新一条数据 String updateSql = "UPDATE user SET username = 'xxxx' WHERE id = 2"; long updateRes = stmt.executeUpdate(updateSql); System.out.