Java连接mysql数据库
2017-08-05 14:44
393 查看
import java.sql.*; //声明Connection对象 Connection con; //驱动程序名 String driver = "com.mysql.jdbc.Driver"; //URL指向要访问的数据库名mydata String url = "jdbc:mysql://127.0.0.1:33/test?useUnicode=true&characterEncoding=UTF-8 //MySQL配置时的用户 String user = "root"; //MySQL配置时的密码 String password = "root"; //遍历查询结果集 try { //加载驱动程序 Class.forName(driver); //1.getConnection()方法,连接MySQL数据库!! con = DriverManager.getConnection(url,user,password); if(!con.isClosed()) System.out.println("Succeeded connecting to the Database!"); //2.创建statement类对象,用来执行SQL语句!! Statement statement = con.createStatement(); //要执行的SQL语句 // String sql = "insert into demo(id,name,pos,salary) values(001,'水电费方','业务','1600') "; //String sql = "insert into demo(id,name,pos,salary) values(?,?,?,?) "; String sql = "insert into weather(address,temperature,weatherstatus,date) values(?,?,?,?) "; PreparedStatement ps=null; ps=con.prepareStatement(sql); ps.setString(1,address); ps.setString(2,temperature); ps.setString(3,weather); ps.setString(4,date); con.close(); con.close(); } catch(ClassNotFoundException e) { //数据库驱动类异常处理 System.out.println("Sorry,can`t find the Driver!"); e.printStackTrace(); } catch(SQLException e) { //数据库连接失败异常处理 e.printStackTrace(); }catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ System.out.println("数据库数据成功获取!!"); } }
String url = “jdbc:mysql://127.0.0.1:33/test?useUnicode=true&characterEncoding=UTF-8 可以解决中文写入数据库乱码问题。建表时把编码方式设置为utf_8
相关文章推荐
- java开发中JDBC连接MySQL数据库代码
- JAVA_WEB项目之在myecplise中如何利用DB Browser窗口连接mysql数据库之后根据表反向生成映射文件
- Java连接MySQL数据库
- window下的java程序连接linux系统的mysql数据库
- Java连接MySql数据库的方法
- Android Java连接MySQL数据库
- java连接mysql数据库的方法
- java服务器连接mysql数据库
- java连接MySql数据库 实现用户登录功能
- java连接MySql数据库
- JAVA连接mysql数据库,动态创建表以及动态插入数据
- JAVA 连接MYSQL数据库
- java中用JDBC进行mysql数据库的连接 步骤 +实例
- Java连接Mysql数据库警告:Establishing SSL connection without server's identity verification is not recommend
- Java JDBC连接mysql数据库详解
- Java连接MySQL数据库
- JAVA连接mysql数据库,动态创建表以及动态插入数据
- JDBC精解--java连接mysql数据库
- Java 通过JDBC连接Mysql数据库的方法和实例【图文说明】
- Java 连接mysql数据库warn:Establishing SSL connection without server's identity verification is not ...