Chinaunix首页 | 论坛 | 博客
  • 博客访问: 22162
  • 博文数量: 22
  • 博客积分: 960
  • 博客等级: 准尉
  • 技术积分: 260
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-06 12:49
文章分类
文章存档

2011年(1)

2009年(21)

我的朋友
最近访客

分类: Java

2009-10-06 13:00:14

1.       首先下载java.jdbc.Driver驱动。配置classpath环境变量,在Eclipse的环境变量路径中添加外部jar

2.       以下为连接代码。

3.       但是默认情况下,mysql是不允许远程访问的.,所以可以用提权命令进行提权操作:

现在需要添加一个可以具有原创访问的mysql账号(需要进入mysql命令行下):

GRANT ALL PRIVILEGES ON *.* TO remote@"%" IDENTIFIED BY '远程登录的明文密码' WITH GRANT OPTION;

执行如下语句生效:

flush privileges;

 

 

import java.sql.*;
public class mysql {
public static void main(String[] args){
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/medicine";
String user = "root";
String password = "hello";
String test = "";

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();
            String sql = "select * from news order by time desc";
            
/*
            String value = "搜狐";
            String sql_insert = "insert into news(sourse,href,title,time) values ('"+value+"','','医疗','2010')";
     try{
          int result = statement.executeUpdate(sql_insert);
         }catch(SQLException ex){
          ex.printStackTrace();
         }
         */

      ResultSet rs = statement.executeQuery(sql);
      System.out.println("-----------------------------------------");
      String name = null;
      while(rs.next())
            {
             name = rs.getString("sourse");
             System.out.println(rs.getString("id")+"\t"+rs.getString("href") + "\t" + name + "\t" + rs.getString("title")+"\t"+rs.getString("time"));
            }

            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();

           }
           System.out.println("-----------------------------------------");
}

}

阅读(292) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~