Chinaunix

标题: Java连接Mysql [打印本页]

作者: 601879456    时间: 2009-10-06 13:00
标题: Java连接Mysql

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 = "http://health.sohu.com/20090828/n266291535.shtml";
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+"','http://www.sohu.com.cn','医疗','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("-----------------------------------------");
}
}


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/104536/showart_2064779.html




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2