zoukankan      html  css  js  c++  java
  • JDBC连接mysql 数据库

     1 package cn.edu.njupt.dbconnection;
     2 
     3 import java.sql.Connection;
     4 import java.sql.DriverManager;
     5 import java.sql.PreparedStatement;
     6 import java.sql.ResultSet;
     7 import java.sql.SQLException;
     8 
     9 
    10 public class DatabaseConnection {
    11 
    12 private static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
    13 private static final String DBURL = "jdbc:mysql://localhost:3306/jdbcdemo";
    14 private static final String DBUSER = "root";
    15 private static final String DBPASSWORD = "mysqladmin";
    16 private Connection conn;
    17 
    18 public DatabaseConnection(){
    19 try {
    20 Class.forName(DBDRIVER);
    21 this.conn = DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD);
    22 } catch (ClassNotFoundException e) {
    23 e.printStackTrace();
    24 } catch (SQLException e) {
    25 e.printStackTrace();
    26 }
    27 }
    28 
    29 public Connection getConnection(){
    30 return this.conn;
    31 }
    32 
    33 public void close(){
    34 if(this.conn != null){
    35 try {
    36 this.conn.close();
    37 } catch (SQLException e) {
    38 e.printStackTrace();
    39 }
    40 }
    41 }
    42 public static void main(String[] args) {
    43 String sql = "create table student(id varchar(5),name varchar(20),primary key(id));";
    44 try {
    45 PreparedStatement pstmt = new DatabaseConnection().getConnection().prepareStatement(sql);
    46 int result = pstmt.executeUpdate();
    47 if(result != -1){//创建成功
    48 System.out.println("数据库 创建 成功");
    49 String sql1 = "insert into student(id,name) values(1,'张三')";
    50 int r1 = pstmt.executeUpdate(sql1);
    51 System.out.println("数据插入 r1 成功");
    52 String sql2 = "insert into student(id,name) values(2,'李四')";
    53 int r2 = pstmt.executeUpdate(sql2);
    54 System.out.println("数据插入 r2 成功");
    55 String sql3 = "select * from student";
    56 ResultSet rs = pstmt.executeQuery(sql3);
    57 System.out.println("学号\t姓名");
    58 while(rs.next()){
    59 System.out.println(rs.getString(1)+"\t"+rs.getString(2));
    60 }
    61 }
    62 new DatabaseConnection().close();
    63 } catch (SQLException e) {
    64 e.printStackTrace();
    65 }
    66 }
    67 
    68 }
  • 相关阅读:
    AndroidStudio中AlertDialog的四种用法(转载)
    ZPL指令封装
    Android程序闪退时写日志并上传到服务器
    sql server 导出表结构
    Kestrel服务器ASP.NetCore 3.1程序启用SSL
    Asp.Net Core 下 Newtonsoft.Json 转换字符串 null 替换成string.Empty(转)
    ApiResult-WebAPI开发统一返回值对象的演化(.net core版)
    EF Core 拓展SqlQuery方法(转载)
    钉钉小程序post提交json,报400、415
    体验.net core 3.1 socket
  • 原文地址:https://www.cnblogs.com/pony1223/p/2813790.html
Copyright © 2011-2022 走看看