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("-----------------------------------------"); }
}
|
阅读(1569) | 评论(2) | 转发(0) |