代码改变世界

java JDBC配置和使用

2012-09-30 17:02  youxin  阅读(9919)  评论(0编辑  收藏  举报

去mysql网站http://dev.mysql.com/downloads/connector/ 下载 JDBC driver

http://dev.mysql.com/doc/refman/5.1/en/connector-j-installing.html

You can install the Connector/J package using either the binary or source distribution. The binary distribution provides the easiest method for installation; the source distribution lets you customize your installation further. With either solution, you manually add the Connector/J location to your Java CLASSPATH.

如何安装呢?

有很多办法。

最简单的办法:

把下载 的文件解压后的  。jar文件 copy到 %JAVA_HOME%\jre\lib\ext 下, %JAVA_HOME就是jdk的安装目录。

这样做之后,每次新建的project 查看 system library 时都会看到 mysql-connector-java-5.1.22-bin.jar这个名字。这正是我们想要的。

 

还可以在单个项目导入这个jar,选择所选的项目,右键点击my--->build Path--->add external Archiver...选择jdbc驱动,确定。这样做很麻烦,下次建造工程又需要jdbc又要导入。

 

还可以选择window->preference->java->bulid path-->classpath 增加jar包。这样做也是一劳永逸。

 

下面是测试的代码:

import java.sql.*;
public class MysqlJdbc {
  public static void main(String args[]) {
    try {
      Class.forName("com.mysql.jdbc.Driver");     //加载MYSQL JDBC驱动程序   
      //Class.forName("org.gjt.mm.mysql.Driver");
     System.out.println("Success loading Mysql Driver!");
    }
    catch (Exception e) {
      System.out.print("Error loading Mysql Driver!");
      e.printStackTrace();
    }
    try {
      Connection connect = DriverManager.getConnection(
          "jdbc:mysql://localhost:3306/test","root","198876");
           //连接URL为   jdbc:mysql//服务器地址/数据库名  ,后面的2个参数分别是登陆用户名和密码

      System.out.println("Success connect Mysql server!");
      Statement stmt = connect.createStatement();
      ResultSet rs = stmt.executeQuery("select * from user");
                                                              //user 为你表的名称
      while (rs.next()) {
        System.out.println(rs.getString("name"));
      }
    }
    catch (Exception e) {
      System.out.print("get data error!");
      e.printStackTrace();
    }
  }
}

注意导入的包是

import java.sql.*; 导入其他的包会错误。
运行结果:

Success loading Mysql Driver!
Success connect Mysql server!

xxx 数据

JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC为工具/数据库开发人员提供了一个标准的API,据此可以构建更高级的工具和接口,使数据库开发人员能够用纯 Java API 编写数据库应用程序,

使用JDBC的步骤分为6步

使用JDBC的步骤1. load the driver

(1)Class.forName()|Class.forName().newlnstance()|new DriverName()

(2)实例化时自动向DriverManager注册,不需要显示调用DriverManager.registerDriver

使用JDBC的步骤2. Connect to the DataBase

DriverManager.getConnection()

使用JDBC的步骤3.Excute the SQL

(1)connection.CreateStatement() 

(2)Statement.excuteQuery()

(3)Statement.executeUpdate()

使用JDBC的步骤4. Retrieve the result data

循环取得结果 while(rs.next())

使用JDBC的步骤5. show the result data

将数据库中的各种类型转换为java中的类型(getXXX)方法

使用JDBC的步骤6. close

close the resultset / close the  statement /close the connection

package DB;     
import java.sql.*;     
class  Jdbc     
{     
    public static void main(String[] args)throws Exception     
    {          
        //只有下面2句话就可以连接到数据库中     
        Class.forName("com.mysql.jdbc.Driver");        
        Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "1234");    //Class.forName("com.mysql.jdbc.Driver");        
        //Connection conn=(Connection) getConnection("jdbc:mysql://localhost:3306/drp", "root", "root");     
 //Class.forName("oracal.jdbc.driver.OracalDriver");     
        //new oracal.jdbc.driver.OracalDriver();     
        //Connection conn=DriverManager.getConnection"jdbc:oracal:thin:@localhost:1521:SXT"."scott","tiger"     
             
        //jdbc.driverClassName=com.mysql.jdbc.Driver;     
        //jdbcjdbc.url=jdbc:mysql:localhost:3306 /test?useUnicode=true&characterEncoding=utf8;     
    }     
}    

 

链接和操作数据库的时候有2个异常要捕获,如下:

import java.sql.*;
public class Jdbc {
    public static void main(String[] args) {     
            
      try {
                Class.forName("com.mysql.jdbc.Driver");     
   
                Connection conn = DriverManager.getConnection(     
                        "jdbc:mysql://localhost:3306/test", "root", "1234");     
   
                Statement stmt = conn.createStatement();     
                ResultSet rs = stmt.executeQuery("select * from test.admin");     
   
                while (rs.next()) {     
                    System.out.println(rs.getString("username"));     
                    System.out.println(rs.getInt("id"));     
                }       
   
                 rs.close();     
              stmt.close();     
               conn.close();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }     
       
  }
}
我们可以先写完代码,写完后全选所写的代码,点击右键选择Surround by try catch ,编译器会自动帮我们把异常语句写好。
注意catch ,我们只要一个try,可以有2个catch语句。


http://blog.csdn.net/zhazha1980518/article/details/6701267
http://lavasoft.blog.51cto.com/62575/20588

 

 maven工程使用JDBC

pom.xml引入

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>

jdbc.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/xx?useUnicode=true&characterEncoding=utf-8&useSSL=false

username=root

password=123456

package common;

import java.io.IOException;
import java.util.Properties;

public class PropertiesUtil {

    static Properties p=new Properties();

    public PropertiesUtil(){

    }
    public static boolean loadFile(String fileName){

        try {
            p.load(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName));
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    public static String getPropertyValue(String key)
    {
        return p.getProperty(key);
    }
}

 

package common;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JdbcUtil {
    private static Connection conn=null;

    public static Connection getConn()
    {
        PropertiesUtil.loadFile("jdbc.properties");
        String driver = PropertiesUtil.getPropertyValue("driver");
        String url = PropertiesUtil.getPropertyValue("url");
        String username  = PropertiesUtil.getPropertyValue("username");
        String password = PropertiesUtil.getPropertyValue("password");

        try{
            Class.forName(driver);
            conn= DriverManager.getConnection(url,username,password);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
            close();
        }
        return conn;

    }
    public static void close(){
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

 

package jdbcLearn;

import common.JdbcUtil;

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

public class jdbcConnecDemo {
    public static void main(String[] args)
    {
        Connection conn= JdbcUtil.getConn();
        String sql="select * from user ";

        Statement stmt=null;
        ResultSet res=null;

        try{

            stmt=conn.createStatement();
            res=stmt.executeQuery(sql);
            while(res.next()){
                Integer id=res.getInt(1);
                String username=res.getString(2);
                System.out.println("id:"+id.toString()+",username:"+username);
            }
            res.close();
            stmt.close();
      conn.close();
} catch (SQLException e) { e.printStackTrace(); } } }

 

如果有报错:

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

解决方法:maven 中clean一下,然后再运行,就可以了。

 

报警输出:

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

原因:

com.mysql.cj.jdbc.Driver是mysql-connector-java 6 中的特性,相比mysql-connector-java 5 多了一个时区:serverTimezone,把数据源配置的驱动改一下就好了

 

如果你的sql有修改,报错:

java sql SQLException Column Index out of range 0 1

问题原因:

由于rs.next()遍历查询结果时,下标是从“1”开始,而这里打印是从“0”开始,导致出错