Home > Database > Mysql Tutorial > body text

MySQL数据库的连接

WBOY
Release: 2016-06-07 15:46:33
Original
1147 people have browsed it

首先,安装mySQL 5.1和mysQL connector 5.1(还可以安装Navicat for MySQL 10,Navicat是MySQL的一个图形操作工具,可以快速建立表和数据库) 然后,建立数据库文件teachweb和表score,依次使用如下命令: create databaseteachweb CHARACTER SET gbk; use t

首先,安装mySQL 5.1和mysQL connector 5.1(还可以安装Navicat for MySQL 10,Navicat是MySQL的一个图形操作工具,可以快速建立表和数据库)

然后,建立数据库文件teachweb和表score,依次使用如下命令:

    create database teachweb CHARACTER SET gbk;
    use teachweb;

    CREATE TABLE ‘score` (

     `ID`  varchar(20) NOT NULL COMMENT '学号' ,

     `ScoreUsername`  varchar(20) NULL COMMENT '课程名称' ,

     `Score`  int(5) NULL ,

     PRIMARY KEY (`ID`)

     );

其次,把下面的代码保存在connectTest.java文件中

//connectTest.java

import java.sql.*;
public class connectTest {
 public static void main(String[] args){
  String driver="com.mysql.jdbc.Driver"; //加载mysql驱动
     String url="jdbc:mysql://localhost:3306/teachweb"; //数据库文件为teachweb
     String username="root";  //用户名
     String password="root";  //用户密码
     
     try {
      Class.forName(driver);
      Connection conn=DriverManager.getConnection(url,username,password);
      if(!conn.isClosed())
       System.out.println("Succeeded connecting to the Database");
      Statement statement=conn.createStatement();
      String sql="select * from score"; //查询score表
      ResultSet rs=statement.executeQuery(sql);
      System.out.println("------------------------");
      String name=null;
      while(rs.next()){
       name=rs.getString("ID");
       name=new String(name.getBytes("ISO-8859-1"),"GB2312"); //转换字符编码
       System.out.println(rs.getString("ScoreUsername")+"\t"+name);
      }
      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();
  }    
    
  
 }
}
最后,点击“开始”--》“运行”--》“cmd”--》输入以下两条命令:

javac connectTest.java

java connectTest.java

或者在MyEclipse8.5中运行connectTest.java

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!