实现Java连接mysql(源码)!

Java连接mysql数据库,代码经过运行准确无误。
下面为实例---->
用数据库操纵工具(例:SQLyogEnt)操纵mysql建表,或dos下建,如下:

数据库名:scutcs
表名:student
表内容:
sno  char[7]  NO NULL Primary Key;
sname  varchar[8]  NO NULL;
sex  char[2]  NO NULL;
bdate  date   NO NULL;
height  decimal[10,0] ;
-------------------------------------------------------------------------
java程序:

import java.sql.*;

public class JDBCTest {

public static void main(String[] args){

          
           String driver = "com.mysql.jdbc.Driver";         // 驱动程序名

         
           String url = "jdbc:mysql://localhost/scutcs";     // URL指向要访问的数据库名scutcs 
         
          
           String user = "........";       // MySQL配置时的用户名
  
           String password = "........";      // MySQL配置时的密码

           try {
           
            Class.forName(driver);    // 加载驱动程序

          
            Connection conn = DriverManager.getConnection(url, user, password);      // 连续数据库

            if(!conn.isClosed())
             System.out.println("Succeeded connecting to the Database!");     //验证是否连接成功

           
            Statement statement = conn.createStatement();               // statement用来执行SQL语句

          
            String sql = "select * from student";                  // 要执行的SQL语句

          
            ResultSet rs = statement.executeQuery(sql);       // 结果集

            System.out.println("-----------------------------------------");
            System.out.println("执行结果如下所示:");
            System.out.println("-----------------------------------------");
            System.out.println(" 学号" + "\t" + " 姓名" + "\t\t" + "性别");
            System.out.println("-----------------------------------------");

            String name = null;

            while(rs.next()) {
   
           
             name = rs.getString("sname");                            // 选择sname这列数据
   
           
             System.out.println(rs.getString("sno") + "\t" + name + "\t" + rs.getString("sex"));        // 输出结果
            }

            rs.close();
            conn.close();

           } catch(ClassNotFoundException e) {


            System.out.println("Sorry,can`t find the Driver!");
            e.printStackTrace();


           } catch(SQLException e) {


            e.printStackTrace();


           } catch(Exception e) {


            e.printStackTrace();


           }
}
}


OK,完美运行!支持中文输出

施杨出品!!!


posted on 2008-07-10 22:14  俱正Steven  阅读(9077)  评论(0编辑  收藏  举报

导航