search
HomeJavajavaTutorialDetailed introduction to java jdbc connection and use

java jdbc connection and use

jdbc

Import driver

//jar is a packaged set of class files that can be referenced in other projects
//Add external jars import in Build Path

Connect to JDBC

1. Load driver

Class.from("com.mysql.jdbc.Driver");

Create connection

//导包使用 java.sql.*;
String jdbc="jdbc:mysql://localhost:3306/student?user=root&password=&characterEncoding=utf-8";//student是表名
Connection conn = DriverManager.getConnection(jdbc);

2. Note that you must remember to close the database after opening it.

conn.close();

1. Execute SQL statements (create table, insert, delete, update)

Use Statemant

Statemant st = conn.createStatemant();
 int row = st.executeUpdate(sql语句);//不能做查询操作。

Use Can PrepareStatement

be used? Placeholders to replace the parameters you need to pass

String sql = "insert into " + TABLENAME
+ "(name,subject,score) values(?,?,?)";
PrepareStatement pt = conn.prepareStatement(sql);
 //给每一位占位符设置值,下标从1开始
 pt.setString(1,score.getName());
 pt.setString(2.score.getSubject());
pt.setDouble(3,score.getScore());
 //使用无参的方法
pt.executeUpdate();

1. Query operation

static List<Score> queryScore(Connection pconn, Score pScore)
      throws SQLException {
    ArrayList<Score> mlist = new ArrayList<>();
    String sql = "select * from " + TABLENAME + " where name = ?";
    PreparedStatement ps = pconn.prepareStatement(sql);
    ps.setString(1, pScore.getName());
    ResultSet rs = ps.executeQuery();
 
    while (rs.next()) {
      // 这里可以通过rs获取所有结果
      String subject = rs.getString("subject");
      int id = rs.getInt("id");
      double score = rs.getDouble("score");
      mlist.add(new Score(id, pScore.getName(), subject, score));
    }
    return mlist;
  }

The following is a small program

//建立数据库连接类
public class DAO {
 
  // 放问数据库的链接地址
  static String jdbc = "jdbc:mysql://localhost:3306/student?user=root&password=&characterEncoding=utf-8";
 
  // 打开链接
  public static Connection connection() {
    // 使用JDBC的步骤
    // 1. 加载JDBC驱动
    try {
      // 类的全名 包名+类名
      Class.forName("com.mysql.jdbc.Driver");
      // 2. 连接数据库
      Connection conn = DriverManager.getConnection(jdbc);
      return conn;
    } catch (Exception e) {
      System.out.println("驱动加载失败");
      return null;
    }
  }
 
 
 
}
 
 
//分数类
public class Score {
 
  String name;
  String id;
  String subject;
  double score;
 
 
 
  public Score(String name, String subject, double score) {
    super();
    this.name = name;
    this.subject = subject;
    this.score = score;
  }
 
 
 
  @Override
  public String toString() {
    return "Score [name=" + name + ", id=" + id + ", subject=" + subject
        + ", score=" + score + "]";
  }
 
 
 
  public Score(String name, String id, String subject, double score) {
    super();
    this.name = name;
    this.id = id;
    this.subject = subject;
    this.score = score;
  }
 
  public String getName() {
    return name;
  }
 
  public void setName(String name) {
    this.name = name;
  }
 
  public String getId() {
    return id;
  }
 
  public void setId(String id) {
    this.id = id;
  }
 
  public String getSubject() {
    return subject;
  }
 
  public void setSubject(String subject) {
    this.subject = subject;
  }
 
  public double getScore() {
    return score;
  }
 
  public void setScore(double score) {
    this.score = score;
  }
 
}
 
 
//实现类
public class Test {
 
 
  public static String TABLENAME = "score";
 
  public static void main(String[] args) {
    try {
      Connection conn = DAO.connection();
      if (conn != null) {
        System.out.println("链接上了");
        // createTable(conn);
        // 插入一条记录
        // Score score = new Score("李四 ", "Android", 98);
        // System.out.println(addScore2(conn, score));
        // deleteScore(conn, score);
        // updateScore(conn, score);
        List<Score> list = queryScoreByName(conn, "王五"); //queryAllScore(conn);
        for (Score score : list) {
          System.out.println(score);
        }
        conn.close();
      } else {
        System.out.println("链接失败 ");
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
 
  // 创建一张表
  public static boolean createTable(Connection conn) {
    // 开始执行sql语句
    String sql = "create table "
        + TABLENAME
        + "(id integer primary key auto_increment,name varchar(3) not null,subject varchar(20) not null,score double)";
    // 要执行一条语句,需要一个执行的类 Statement
    try {
      Statement st = conn.createStatement();
      int result = st.executeUpdate(sql);
      System.out.println(result);
      if (result != -1)
        return true;
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return false;
  }
 
  // 添加一条记录
  public static boolean addScore(Connection conn, Score score)
      throws SQLException {
    String sql = "insert into " + TABLENAME
        + "(name,subject,score) values(&#39;" + score.getName() + "&#39;,&#39;"
        + score.getSubject() + "&#39;," + score.getScore() + ")";
    System.out.println(sql);
    Statement st = conn.createStatement();
    int row = st.executeUpdate(sql);
    if (row > 0)
      return true;
    return false;
  }
 
  // 添加一条记录2
  public static boolean addScore2(Connection conn, Score score)
      throws SQLException {
    // 占位符?来代替需要设置的参数
    String sql = "insert into " + TABLENAME
        + "(name,subject,score) values(?,?,?)";
    PreparedStatement ps = conn.prepareStatement(sql);
    // 必须给定?所代表的值
    ps.setString(1, score.getName());
    ps.setString(2, score.getSubject());
    ps.setDouble(3, score.getScore());
    // 调用无参的方法
    int row = ps.executeUpdate();
    if (row > 0)
      return true;
    return false;
  }
 
  public static boolean deleteScore(Connection conn, Score score)
      throws SQLException {
    String sql = "delete from " + TABLENAME + " where name=? and subject=?";
    // 创建PrepareStatement
    PreparedStatement ps = conn.prepareStatement(sql);
    ps.setString(1, score.getName());
    ps.setString(2, score.getSubject());
    // ps.setDouble(3, score.getScore());
    // 执行
    int row = ps.executeUpdate();
    System.out.println(row);
    if (row > 0)
      return true;
    return false;
  }
 
  public static boolean updateScore(Connection conn, Score score)
      throws SQLException {
    // 修改 score人他的科目的成绩
    String sql = "update " + TABLENAME
        + " set score=? where name=? and subject=?";
    PreparedStatement ps = conn.prepareStatement(sql);
    ps.setDouble(1, score.getScore());
    ps.setString(2, score.getName());
    ps.setString(3, score.getSubject());
    int row = ps.executeUpdate();
    System.out.println(row);
    if (row > 0)
      return true;
    return false;
  }
 
  public static List<Score> queryAllScore(Connection conn)
      throws SQLException {
    String sql = "select * from " + TABLENAME;
    // 开始查询
    Statement st = conn.createStatement();
    ResultSet rs = st.executeQuery(sql);
    List<Score> list = new ArrayList<Score>();
    while (rs.next()) {
      // 这里可以通过rs获取所有结果
      String id = rs.getString("id");
      String name = rs.getString("name");
      String subject = rs.getString("subject");
      double score = rs.getDouble("score");
      list.add(new Score(name, id, subject, score));
    }
    // 结束
    return list;
  }
 
  public static List<Score> queryScoreByName(Connection conn, String name)
      throws SQLException {
    String sql = "select * from " + TABLENAME + " where name=?";
    PreparedStatement pt = conn.prepareStatement(sql);
    pt.setString(1, name);
    ResultSet rs = pt.executeQuery();
    List<Score> list = new ArrayList<>();
    while (rs.next()) {
      String subject = rs.getString("subject");
      String id = rs.getString("id");
      double score = rs.getDouble("score");
      list.add(new Score(name, id, subject, score));
    }
    return list;
  }

For more java jdbc connection and usage details, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does the class loader subsystem in the JVM contribute to platform independence?How does the class loader subsystem in the JVM contribute to platform independence?Apr 23, 2025 am 12:14 AM

The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

Does the Java compiler produce platform-specific code? Explain.Does the Java compiler produce platform-specific code? Explain.Apr 23, 2025 am 12:09 AM

The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

How does the JVM handle multithreading on different operating systems?How does the JVM handle multithreading on different operating systems?Apr 23, 2025 am 12:07 AM

Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.

What does 'platform independence' mean in the context of Java?What does 'platform independence' mean in the context of Java?Apr 23, 2025 am 12:05 AM

Java's platform independence means that the code written can run on any platform with JVM installed without modification. 1) Java source code is compiled into bytecode, 2) Bytecode is interpreted and executed by the JVM, 3) The JVM provides memory management and garbage collection functions to ensure that the program runs on different operating systems.

Can Java applications still encounter platform-specific bugs or issues?Can Java applications still encounter platform-specific bugs or issues?Apr 23, 2025 am 12:03 AM

Javaapplicationscanindeedencounterplatform-specificissuesdespitetheJVM'sabstraction.Reasonsinclude:1)Nativecodeandlibraries,2)Operatingsystemdifferences,3)JVMimplementationvariations,and4)Hardwaredependencies.Tomitigatethese,developersshould:1)Conduc

How does cloud computing impact the importance of Java's platform independence?How does cloud computing impact the importance of Java's platform independence?Apr 22, 2025 pm 07:05 PM

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

What role has Java's platform independence played in its widespread adoption?What role has Java's platform independence played in its widespread adoption?Apr 22, 2025 pm 06:53 PM

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

How do containerization technologies (like Docker) affect the importance of Java's platform independence?How do containerization technologies (like Docker) affect the importance of Java's platform independence?Apr 22, 2025 pm 06:49 PM

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),