Java basic development JDBC operation database addition, deletion, modification and query, detailed explanation of paging query examples

The operations on the database are nothing more than additions, deletions, modifications and queries, among which the numerical query operation is the most complex, so the query will be explained separately. The Mysql database I use here Add, delete, modify and check operations Paging query operation 1. Query results are returned in list 2. Query results are returned as jsonArray 3. Query the total number of records Let’s take a look at the relevant configuration information first public static final String USER_NAME = “root”; public static final String PWD = “123456789”; public static final String DRIVER = “com.mysql.jdbc.Driver”; public static final String URL = “jdbc:mysql://localhost:3306/web_demon”; /** Paging query default number of records per page */ public static final int PAGE_SIZE_DEFAULT = 10; Add, delete, and modify operations Get the database connection object /** * Get database connection * @return database connection object */ public Connection getConnection(Connection conn) { if(cOnn== null){ try { Class.forName(Config.DRIVER); cOnn= DriverManager.getConnection(Config.URL, Config.USER_NAME, Config.PWD); } catch (Exception e) { e.printStackTrace(); } } return conn; } Encapsulate addition, deletion and modification operations /** * Add, delete, insert operations * @param sql sql statement executed * For example: add the statement “insert into user (name,sex) values ​​(?,?)”; * Delete…

Java connects to Mongodb to implement addition, deletion, modification and query

The example in this article shares with you the specific code for connecting java to Mongodb to implement addition, deletion, modification and query for your reference. The specific content is as follows 1. Create a maven project org.mongodb mongodb-driver 3.4.1 2. Write code 1. Query all package com.czxy.mongodb; import com.alibaba.fastjson.JSON; import com.mongodb.*; import java.util.List; import java.util.Set; public class Find { public static void main(String[] args) { //Client link MongoClient mOngodbClint= new MongoClient(“localhost”, 27017); // Get all databases List databaseNames = mongodbClint.getDatabaseNames(); for (String databaseName : databaseNames) { System.out.println(“Database Name “+databaseName); } //Connect to the specified database DB db = mongodbClint.getDB(“text”); //Get all collection names under the current database Set collectiOnNames= db.getCollectionNames(); for (String dbname : collectionNames) { System.out.println(“Collection name “+dbname); } // Connect to the specified collection DBCollection collection = db.getCollection(“stus”); //Data collection information DBCursor dbObjects = collection.find(); while (dbObjects.hasNext()){ //Read data DBObject next = dbObjects.next(); // json format conversion Stus parse = JSON.parseObject(next.toString(), Stus.class); // data output System.out.println(parse); } } } 2. Add data package com.czxy.mongodb; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import java.util.HashMap; import java.util.Map; public class Insert { public static void main(String[] args) { // Get connection MongoClient mOngodbClint= new MongoClient(“localhost”, 27017); // Connect to…

How to use java to operate mysql to implement addition, deletion, modification and query

The example in this article describes the method of using java to operate mysql to implement addition, deletion, modification and query. Share it with everyone for your reference, the details are as follows: First, you need to import the jar package that connects MySQL and Java (mysql-connector-java-5.1.6-bin.jar) into the project. package com.cn.edu; import java.beans.Statement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class helloworld { private Connection cOnn= null; PreparedStatement statement = null; // connect to MySQL void connSQL() { String url = “jdbc:mysql://localhost:3306/hello?characterEncoding=UTF-8”; String username = “root”; String password = “root”; //Load the driver to connect to the database try { Class.forName(“com.mysql.jdbc.Driver” ); cOnn= DriverManager.getConnection( url,username, password ); } //Catch loading driver exception catch (ClassNotFoundException cnfex) { System.err.println( “Failed to load JDBC/ODBC driver.” ); cnfex.printStackTrace(); } //Catch database connection exception catch (SQLException sqlex) { System.err.println( “Unable to connect to database” ); sqlex.printStackTrace(); } } // disconnect to MySQL void deconnSQL() { try { if (conn != null) conn.close(); } catch (Exception e) { System.out.println(“Close database problem:”); e.printStackTrace(); } } // execute selection language ResultSet selectSQL(String sql) { ResultSet rs = null; try { statement = conn.prepareStatement(sql); rs = statement.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); }…

Java links mySQL database for addition, deletion, modification and query

Java link mySQL database code Modify and check are the same for adding public class JDBCTest {/** * ResultSet encapsulates the JDBC result set, the result of the query */@Testpublic void testResultSet() {Connection cOnnection= null;Statement statement = null;ResultSet rs = null;try {cOnnection = JDBCTools.getConnection();statement = (Statement) connection.createStatement();String sql = “SELECT * FROM jdbc_1”;rs = statement.executeQuery(sql);while (rs.next()) {System.out.print(rs.getInt(1) + “\t”);System.out.print(rs.getString(2) + “\t” );System.out.print(rs.getString(3));System.out.println();}} catch (Exception e) {e.printStackTrace ();} finally {JDBCTools.release(rs, statement, connection);}}/** * Universal update method * @throws SQLException */public void updata(String sql) throws SQLException {Connection cOnnection= null;Statement statement = null;try {cOnnection= getConnection();// Get Statement objectstatement = (Statement) connection.createStatement();// Execute sql statementstatement.executeUpdate(sql);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {try {// Close the statement objectif (statement != null) {statement.close();}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {// Close the database connectionif (connection != null) {connection.close();}}}}/* * * 1. Insert data into the specified table through jdbc * * @throws Exception * */@Testpublic void testStatement() throws Exception {// Get the database linkConnection cOnnection= null;Statement statement = null;try {cOnnection= getConnection();// The sql statement to be executedString sql = “INSERT INTO jdbc_1 (jname,addr) VALUE (‘Li Li’,’Hunjiang City’)”;// Get the Statement objectstatement = (Statement) connection.createStatement() ;//Execute sql statementstatement.executeUpdate(sql);} catch (Exception e)…

java database ppt, java database addition, deletion, modification and query

List of contents of this article: 1. How to upload and download ppt on java web? Does it need to be uploaded to the server? Excel can do it, but how to save this ppt to the database? 2. How to use JAVA to connect to the database? 3. Java reads the jpg uploaded by the user. pdf, doc, xls, ppt files, store the binary data of these files in the database, or store them in file form How to upload and download ppt on java web? Does it need to be uploaded to the server? Excel can do it, but how to save this ppt to the database? If you upload it, it must be uploaded to the server. Otherwise, where can you save it? The file can be converted into binary, and the file can be stored in the database as blob type, but this is not recommended as it will reduce the database performance. Generally, it is stored in a special place on the server, and only the path, upload time and other information are saved in the database How to use JAVA to connect to the database? 1. Load the driver. 2. Create a connection object.…

JavaWEB’s JDBC connection database addition, deletion, modification and query

JavaWEB’s JDBC connection database addition, deletion, modification and query

Database operation based on Myeclipse (not importing the driver into tomcat) 1>Create a new java Web project. Right-click the project project new->folder and name it lib (used to store the jdbc driver) 2>Find the driver (mysql-connector-java-5.0.4-bin.jar) and import it into lib, rightkey Click driver->build path->add build path. If you see a file that looks like a milk bottle, it means the import is successful, that is, the database driver is now ready for use 3>Open mysql create database books; create table book(name varchar(15),id int); 4>Write a program to add, delete, modify and check (take the java program as an example, the writing in java web is similar) package com; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Scanner; import com.mysql.jdbc.Connection; import com.mysql.jdbc.PreparedStatement; import com.mysql.jdbc.ResultSet; public class test { public static void main(String[] args) throws ClassNotFoundException, SQLException { Insert1(123456,“pan”); //Query1(); } public static void Insert1(int id,String na) throws ClassNotFoundException, SQLException{ Connection cOnn=null; Class.forName(“com.mysql.jdbc.Driver”); cOnn=(Connection) DriverManager.getConnection(“jdbc:mysql://localhost:3306/book”,“root”,“123456” ); String sql=“insert into b(name,id)values(?,?)”; PreparedStatement pst=(PreparedStatement) conn.prepareStatement(sql); pst.setString(1,na); pst.setInt(2,id); pst.executeUpdate(); if(conn!=null){ conn.close(); } } public static void Query1() throws ClassNotFoundException, SQLException{ Connection cOnn=null; Class.forName(“com.mysql.jdbc.Driver”); cOnn=(Connection) DriverManager.getConnection(“jdbc:mysql://localhost:3306/book”,“root”,“123456” ); String sql=“select * from b”; PreparedStatement pst=(PreparedStatement) conn.prepareStatement(sql); ResultSet rs=(ResultSet) pst.executeQuery(); while(rs.next()){ int c=rs.getInt(2); String name=rs.getString(1); System.out.println(c+“,”+name+“,”); } if(conn!=null){ conn.close(); }…

Java connects to oracle for addition, deletion, modification and query

Java connects to oracle for addition, deletion, modification and query

1. Add class OraclePersionDao to the DAO layer package com.test.dao;import java.sql.*;/** * Created by wdw on 2017/9/16. */public class OraclePersionDao { // Database driver class private String dbDriver = “oracle.jdbc.driver.OracleDriver”; //Connect to database url private String dbURL = “jdbc:oracle:thin:@192.168.31.128:1521:orcl “; // Username to connect to the database private String dbUser = “PHIP”; //Connect to database password private String dbPwd = “PHIP”; // Get the database connection method and return the Connection object private Connection con = null; //Data execution statement private Statement stat = null; private String sql = null; private ResultSet rs = null; //Create database connection public Connection getDBConnect() { try {// Load database driver Class.forName(dbDriver); con = DriverManager.getConnection(dbURL, dbUser, dbPwd); } catch (Exception e) { System.out.println(e); } return con; } //Add public void Add() { con = getDBConnect(); sql = “insert into sys_users(id,code,name )” + “values(‘1′,’lucy’,’w’)”; try { stat = con.createStatement(); stat.executeUpdate(sql); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //Delete public void Delete( ) { con = getDBConnect(); sql = “delete from sys_users ” + “where ID=1”; try { stat = con.createStatement(); stat.executeUpdate(sql); } catch (SQLException e) {// TODO Auto-generated catch block e.printStackTrace(); } } //Modify public void Update() { con…

Simple addition, deletion, modification and query of java code, javaweb implements simple addition, deletion, modification and query

Requesting a simple JAVA code to request a adding, deleting, modifying and checking code for the employee salary management system, thank you Add, delete, modify and check the database? The following is sql server 2013+java. It implements the addition, deletion, modification and query of MSC objects. You need to download the connection driver: com.microsoft.sqlserver.jdbc.SQLServerDriver p> Just search online import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement ; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; class MSC { public String MscID; public String MscName; public String MscCompany; public float MscLongitude; public float MscLatitude; public float MscAltitude; public MSC(String MscID, String MscName, String MscCompany, float MscLongitude, float MscLatitude, float MscAltitude){ this.MscID = MscID; this.MscName = MscName; this.MscCompany = MscCompany ; this.MscLOngitude=MscLongitude; this.MscLatitude = MscLatitude; this.MscAltitude = MscAltitude; } p> } public class sqlserverjdbc { public Connection getConnection(){ String driverName = “com.microsoft.sqlserver.jdbc.SQLServerDriver “; //Load the JDBC driver String dbURL = “jdbc:sqlserver://localhost:1433; DatabaseName=gsm”; //Connect the server and database sample String userName = “sa”; //Default username String userPwd = “123”; //Password Connection dbCOnn= null; try { Class.forName(driverName); dbCOnn=DriverManager.getConnection(dbURL, userName, userPwd); } catch (Exception e) { e.printStackTrace(); } return dbConn; } public void printUserInfo(){ Connection con = getConnection(); Statement sta = null; ResultSet rs = null; System.out.println(“Print Table MSC…

Javaweb comprehensive exercise one (simple addition, deletion, modification and query)

Javaweb comprehensive exercise one (simple addition, deletion, modification and query)

Article directory Add Add contacts Related codes Delete Delete a single contact Code implementation Delete selected Code implementation Change Modify contact Related codes Check Page query Add Add Contact The picture below is the process idea of ​​adding a contact: The first thing is to set the encoding, because there is Chinese input Then get all the data Then the encapsulation object (I have not written the object, the object is the user entity class created by myself) Then call the add method of service to save it to the database. Jump again (because after adding it, you will return to the main interface for querying all users) Relatedcode Thefirstis packageweb.Servlet;import domain.user;import org. apache.commons.beanutils.BeanUtils;import service.impl.userServiceimpl;import javax.servlet .ServletException;import javax.servlet. annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet .http.HttpServletRequest;import javax. servlet.http.HttpServletResponse ;import java.io.IOException;import java.lang .reflect.InvocationTargetException;import java. util.Map;@WebServlet(“/adduserServlet”)public class adduserServlet extends HttpServlet{ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding (“utf-8”); Map<String , String[]> map = request.getParameterMap(); user user = new user(); try { BeanUtils.populate(user, map); } catch (IllegalAccessException e) { e. printStackTrace(); } catch (InvocationTargetException e) { e .printStackTrace(); } userServiceimpl serviceimpl = new userServiceimpl(); serviceimpl.add(user); response.sendRedirect(request.getContextPath()+“/findUserByPageServlet”); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException span> { this.doPost(request, response ); }} public…

javabasedao, general addition, deletion, modification and query

javabasedao, general addition, deletion, modification and query

2019 Unicorn companies spend heavily to recruit Python engineers>>> package com.ts.dao;import java.sql.*;public class BaseDao {protected Connection conn = null;protected PreparedStatement pstmt = null;protected ResultSet rs = null;public void getConnection() {try {Class.forName(“com.mysql.jdbc.Driver”);} catch (ClassNotFoundException e) {e.printStackTrace() ;}try {conn = DriverManager.getConnection(“jdbc:mysql://localhost:3306/ts?useUnicode=true&characterEncoding=utf-8”, “root”, “ok”);} catch (SQLException e) {e.printStackTrace();}} public void closeAll() {try {if (rs != null) {rs.close();}if (pstmt != null) { pstmt.close();}if (conn != null) {conn.close();}} catch (SQLException e) {e.printStackTrace();}}//General addition, deletion and modification public int executeUpdateSQL(String sql, Object[] param) {int num = 0;try {getConnection();pstmt = conn.prepareStatement(sql);if (param != null) {for (int i & #61; 0; i <param.length; i++) {pstmt.setObject(i + 1, param[i]);}}num = pstmt.executeUpdate() ;} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {closeAll();}return num;}//General query public void executeQuerySQL(String sql, Object[] param) { try {getConnection();pstmt = conn.prepareStatement(sql);if (param != null) {for (int i = 0; i <param.length; i+& #43;) {pstmt.setObject(i + 1, param[i]);}}rs = pstmt.executeQuery();} catch (SQLException e) {e.printStackTrace();}} } Redirect: https://my.oschina.net/u/1264926/blog/170734

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索