JDBC实现操作MsSql数据库实例

项目目录结构:

src
   com
      demo
          model
                  Student.java
                  
   database
           DBConnection.java
           User.java
           UserDAO.java
           
WebContent
       action.jsp
       index.jsp
       submit.jsp
           
    WEB-INF
        lib
                sqljdbc4.jar

 

数据库结构:

create table t_user(
    [id]  [int] not NULL primary key,
    [name]  [varchar](50) not NULL
)

模型Student.java

package com.demo.model;

public class Student {
    public String Name;
}

数据库访问:

DBConnection.java

package database;
import java.sql.*;
import java.sql.Statement;

public class DBConnection {
    private static final String URL = "jdbc:sqlserver://127.0.0.1:1433;databaseName=Sample;";

    private static final String USERNAME = "sa";

    private static final String PASSWORD = "******";

    private static final String DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";

    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
    }

    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        try {
            if(connection != null) {
                connection.close();
            }
            if(statement != null) {
                statement.close();
            }
            if(resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(Connection connection, Statement statement) {
        close(connection, statement, null);
    }
}

User.java

package database;

public class User {
    private int id;

    private String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public User(String name) {
        this.name = name;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getId() {
        return this.id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    @Override
    public String toString() {
        return "#" + id + " name: " + name;
    }
}
View Code

相关文章:

  • 2022-01-09
  • 2021-11-05
  • 2021-11-17
  • 2021-09-14
  • 2022-12-23
  • 2022-12-23
  • 2022-01-14
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-05-20
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-09
  • 2022-12-23
相关资源
相似解决方案