免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1503 | 回复: 0
打印 上一主题 下一主题

Java连接Mysql [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-10-06 13:00 |只看该作者 |倒序浏览

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
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP