MySQL JBDC 连接测试

package cn.xh.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Demo01 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Statement st=null;
        Connection conn=null;
            
        try {
            //1.加载MYSQL 数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.创建连接
            //定义链接(注意设置编码UTF-8)
             //String url ="jdbc:mysql://192.168.47.10:3306/students?user=root&password=123456.&useUnicode=true&characterEncoding=utf8" ;
             String user= "root";  //定义用户
             String password="123456";  //定义密码  --studentss  是数据库
             String url2="jdbc:mysql://192.168.47.10:3306/students?useUncode=trun&characterEncoding=UTF-8";  //定义地址
             System.out.println("开始连接当中......");
             conn = DriverManager.getConnection(url2,user,password);   //连接参数
             System.out.println("连接成功!");
                              
            //3.创建 statement,执行操作
             
             String sql = "INSERT INTO tb_stu(id,NAME,sex,birthday,age) VALUES(15,'大王','男','2013-6-3','8')";
             st =    conn.createStatement(); 
             int result =  st.executeUpdate(sql);
        
             System.out.println(result);
                
            
            
            
        } catch (ClassNotFoundException e) {
                e.printStackTrace();
        }catch (SQLException e) {
                e.printStackTrace();
        }
        finally {
            if(st !=null) {
            try {
                st.close();
            } catch (SQLException e) {
                // TODO: handle exception
                e.printStackTrace();
            }
            }
            if(conn !=null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }    
        }
        
    }
    }

 

posted @ 2021-10-07 17:00  方面盘  阅读(72)  评论(0编辑  收藏  举报