利用java.sql包--访问和处理数据库数据

这篇具有很好参考价值的文章主要介绍了利用java.sql包--访问和处理数据库数据。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

  • java.sql

The java.sql package in Java provides the API for interacting with relational databases using JDBC (Java Database Connectivity). JDBC is a standard Java API that allows Java programs to connect to and interact with various database management systems (DBMS) using SQL (Structured Query Language).
The java.sql package contains several important interfaces and classes that facilitate database connectivity and operations. Here are some of the key classes and interfaces in the java.sql package:
Connection: Represents a connection to a specific database. It provides methods for creating statements, managing transactions, and controlling connection properties.
Statement: Represents a simple SQL statement that is sent to the database for execution. It provides methods for executing SQL queries, updates, and other operations.
PreparedStatement: A subinterface of Statement that represents a precompiled SQL statement with placeholders for input parameters. It allows efficient execution of parameterized queries and provides protection against SQL injection.
CallableStatement : a subinterface of PreparedStatement that specifically handles calling stored procedures or functions.
ResultSet: Represents a table of data resulting from an SQL query. It provides methods to navigate through the result set and retrieve data from the columns.
ResultSetMetaData: Provides information about the columns in a ResultSet, such as column names, types, and properties.
DriverManager: A utility class that manages the available JDBC drivers. It provides methods for registering and retrieving JDBC drivers, as well as establishing database connections.
SQLException: The exception class used by JDBC to report errors related to database operations.
These are just a few examples of the classes and interfaces in the java.sql package. By utilizing these classes and interfaces, you can establish connections to databases, execute SQL statements, retrieve and process query results, and handle exceptions that may occur during database operations.
It's important to note that the java.sql package provides the core JDBC functionality, but the actual database-specific drivers, such as the Microsoft SQL Server JDBC driver (com.microsoft.sqlserver.jdbc.SQLServerDriver), need to be obtained from the respective database vendors and added to the classpath to connect to specific databases.

// Use the connection to execute SQL statements
Once you have established a connection using the com.microsoft.sqlserver.jdbc.SQLServerDriver, you can use the connection object to execute SQL statements. Here's an example of executing a simple SQL query:

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

public class SQLServerExample {
    public static void main(String[] args) {
        String jdbcUrl = "jdbc:sqlserver://localhost:1433;databaseName=mydatabase;";
        String username = "myusername";
        String password = "mypassword";

        try {
            // Load the SQL Server JDBC driver
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

            // Establish a connection
            Connection connection = DriverManager.getConnection(jdbcUrl, username, password);

            // Create a statement
            Statement statement = connection.createStatement();

            // Execute a query
            String sql = "SELECT * FROM employees";
            ResultSet resultSet = statement.executeQuery(sql);

            // Process the query results
            while (resultSet.next()) {
                String employeeName = resultSet.getString("name");
                int employeeAge = resultSet.getInt("age");
                System.out.println("Name: " + employeeName + ", Age: " + employeeAge);
            }

            // Close the result set, statement, and connection
            resultSet.close();
            statement.close();
            connection.close();
        } catch (ClassNotFoundException e) {
            System.out.println("SQL Server JDBC driver not found");
        } catch (SQLException e) {
            System.out.println("Failed to connect to the database: " + e.getMessage());
        }
    }
}
In the example above, after establishing the connection, we create a Statement object using the connection.createStatement() method. With the Statement object, we execute a SQL query using the executeQuery() method and store the results in a ResultSet. Then, we iterate over the ResultSet to retrieve and process the query results.
Remember to handle exceptions appropriately, such as catching SQLException and ClassNotFoundException, and closing the result set, statement, and connection after you're done with them to release any resources they hold.

  • Statement 

In Java, the Statement interface is part of the JDBC API and is used to execute SQL statements and interact with a database. It provides methods to execute SQL queries, updates, and other database operations. The Statement interface represents a simple SQL statement that doesn't include any parameters.
Here are some key methods provided by the Statement interface:
executeQuery(String sql): Executes an SQL SELECT query and returns a ResultSet object containing the query results.
executeUpdate(String sql): Executes an SQL INSERT, UPDATE, or DELETE statement and returns the number of affected rows.
execute(String sql): Executes any SQL statement and returns a boolean value indicating the type of the first result (true if it is a ResultSet, false if it is an update count or there are no results).
addBatch(String sql): Adds an SQL statement to the current batch for batch processing.
executeBatch(): Executes the current batch of statements and returns an array of update counts for each statement.
close(): Releases any resources associated with the Statement object.
Here's an example that demonstrates the usage of Statement to execute a simple SQL query:

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

public class StatementExample {
    public static void main(String[] args) {
        String jdbcUrl = "jdbc:sqlserver://localhost:1433;databaseName=mydatabase;";
        String username = "myusername";
        String password = "mypassword";

        try {
            // Load the SQL Server JDBC driver
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

            // Establish a connection
            Connection connection = DriverManager.getConnection(jdbcUrl, username, password);

            // Create a statement
            Statement statement = connection.createStatement();

            // Execute a query
            String sql = "SELECT * FROM employees";
            ResultSet resultSet = statement.executeQuery(sql);

            // Process the query results
            while (resultSet.next()) {
                String employeeName = resultSet.getString("name");
                int employeeAge = resultSet.getInt("age");
                System.out.println("Name: " + employeeName + ", Age: " + employeeAge);
            }

            // Close the result set, statement, and connection
            resultSet.close();
            statement.close();
            connection.close();
        } catch (ClassNotFoundException e) {
            System.out.println("SQL Server JDBC driver not found");
        } catch (SQLException e) {
            System.out.println("Failed to connect to the database: " + e.getMessage());
        }
    }
}
In the example, after creating a Statement object using connection.createStatement(), we execute an SQL query by calling executeQuery() with the SQL statement. The query results are retrieved as a ResultSet, and we iterate over the result set to process the data.
Remember to handle exceptions appropriately, such as catching SQLException and ClassNotFoundException, and close the result set, statement, and connection after you're done using them to release any resources they hold.

  • PreparedStatement

PreparedStatement is a subinterface of the Statement interface in the java.sql package. It represents a precompiled SQL statement that can accept input parameters. The use of PreparedStatement is recommended when you need to execute a SQL statement multiple times with different parameter values, as it provides better performance and security compared to regular Statement objects.
Here's an example of how to use PreparedStatement to execute a parameterized SQL query:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class PreparedStatementExample {
    public static void main(String[] args) {
        String jdbcUrl = "jdbc:sqlserver://localhost:1433;databaseName=mydatabase;";
        String username = "myusername";
        String password = "mypassword";

        try {
            // Load the SQL Server JDBC driver
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

            // Establish a connection
            Connection connection = DriverManager.getConnection(jdbcUrl, username, password);

            // Create a PreparedStatement
            String sql = "SELECT * FROM employees WHERE age > ?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            // Set parameter values
            int minimumAge = 30;
            preparedStatement.setInt(1, minimumAge);

            // Execute the query
            ResultSet resultSet = preparedStatement.executeQuery();

            // Process the query results
            while (resultSet.next()) {
                String employeeName = resultSet.getString("name");
                int employeeAge = resultSet.getInt("age");
                System.out.println("Name: " + employeeName + ", Age: " + employeeAge);
            }

            // Close the result set, statement, and connection
            resultSet.close();
            preparedStatement.close();
            connection.close();
        } catch (ClassNotFoundException e) {
            System.out.println("SQL Server JDBC driver not found");
        } catch (SQLException e) {
            System.out.println("Failed to connect to the database: " + e.getMessage());
        }
    }
}
In the example, we create a PreparedStatement by calling connection.prepareStatement(sql), where sql is the parameterized SQL query. The SQL query contains a placeholder (?) for the parameter value.
We then set the value for the parameter using preparedStatement.setInt(index, value), where index is the position of the parameter in the query (starting from 1) and value is the actual value.
Finally, we execute the query by calling preparedStatement.executeQuery(), retrieve the query results using a ResultSet, and process the data as needed.
By using a PreparedStatement, you can easily reuse the same SQL statement with different parameter values, improving performance and protecting against SQL injection attacks.

  • CallableStatement 

CallableStatement is another subinterface of the PreparedStatement interface in the java.sql package. It represents a precompiled SQL statement that can be used to execute stored procedures or functions in a database.
Stored procedures are precompiled database objects that contain one or more SQL statements and are typically used to encapsulate complex database operations. Callable statements allow you to invoke these stored procedures and retrieve the results, if any.
Here's an example of how to use CallableStatement to execute a stored procedure:

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Types;

public class CallableStatementExample {
    public static void main(String[] args) {
        String jdbcUrl = "jdbc:sqlserver://localhost:1433;databaseName=mydatabase;";
        String username = "myusername";
        String password = "mypassword";

        try {
            // Load the SQL Server JDBC driver
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

            // Establish a connection
            Connection connection = DriverManager.getConnection(jdbcUrl, username, password);

            // Prepare the stored procedure call
            String storedProcedure = "{call getEmployeeCount(?)}";
            CallableStatement callableStatement = connection.prepareCall(storedProcedure);

            // Register the output parameter
            callableStatement.registerOutParameter(1, Types.INTEGER);

            // Execute the stored procedure
            callableStatement.execute();

            // Retrieve the output parameter value
            int employeeCount = callableStatement.getInt(1);
            System.out.println("Employee Count: " + employeeCount);

            // Close the statement and connection
            callableStatement.close();
            connection.close();
        } catch (ClassNotFoundException e) {
            System.out.println("SQL Server JDBC driver not found");
        } catch (SQLException e) {
            System.out.println("Failed to connect to the database: " + e.getMessage());
        }
    }
}
In the example above, we prepare a CallableStatement by calling connection.prepareCall(storedProcedure), where storedProcedure is the SQL statement representing the stored procedure call. The SQL statement uses the syntax {call procedure_name(?)}, where procedure_name is the name of the stored procedure, and ? represents an input or output parameter.
We then register the output parameter using callableStatement.registerOutParameter(parameterIndex, sqlType), where parameterIndex is the index of the parameter in the SQL statement (starting from 1), and sqlType is the SQL type of the parameter.
Next, we execute the stored procedure by calling callableStatement.execute(). If the stored procedure has any output parameters, we can retrieve their values using methods such as getInt(), getString(), etc., based on the parameter index.
Finally, we close the CallableStatement and the connection.
By using CallableStatement, you can execute stored procedures and retrieve any output parameters or result sets returned by the stored procedure.
getEmployeeCount
The getEmployeeCount is a hypothetical example of a stored procedure name used in the previous code snippet. It represents a stored procedure that returns the count of employees in a database.
In the example code, the stored procedure is invoked using a CallableStatement object with the SQL statement "{call getEmployeeCount(?)}". The question mark (?) is a placeholder for an output parameter, which will hold the count of employees returned by the stored procedure.
The line callableStatement.registerOutParameter(1, Types.INTEGER) registers the output parameter at index 1 with the SQL type Types.INTEGER, indicating that the expected result is an integer value.
After executing the stored procedure with callableStatement.execute(), the code retrieves the output parameter's value using callableStatement.getInt(1). The getInt(1) method retrieves the value of the output parameter at index 1, which corresponds to the employee count returned by the stored procedure.
In a real-world scenario, the getEmployeeCount stored procedure might be implemented in the database, and the code would execute it to retrieve the employee count. The actual implementation of the stored procedure and the logic for retrieving the employee count would depend on the specific database system and the requirements of the application.
 getEmployeeCount stored procedure
To provide an example of a possible implementation of the getEmployeeCount stored procedure, let's assume a Microsoft SQL Server database. Here's a hypothetical implementation using T-SQL:

CREATE PROCEDURE getEmployeeCount
    @employeeCount INT OUTPUT
AS
BEGIN
    SELECT @employeeCount = COUNT(*) FROM employees;
END
In this example, the getEmployeeCount stored procedure is created with one output parameter @employeeCount. The procedure retrieves the count of rows in the employees table using the COUNT(*) aggregate function and assigns the result to the output parameter.
When executing the stored procedure from Java using CallableStatement, the @employeeCount output parameter is registered as an output parameter using callableStatement.registerOutParameter(1, Types.INTEGER). The stored procedure is then executed using callableStatement.execute(), and the employee count can be retrieved using callableStatement.getInt(1).
Please note that the actual implementation of the getEmployeeCount stored procedure may vary based on your specific database schema, table names, and requirements. The above example provides a general outline of how the stored procedure can be created to retrieve the employee count.

  • ResultSetMetaData

The ResultSetMetaData interface in the java.sql package provides information about the columns in a ResultSet object. It allows you to retrieve details such as the column names, types, sizes, and other properties of the result set's columns.
Here's an example of how to use ResultSetMetaData to retrieve column information from a ResultSet:

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

public class ResultSetMetaDataExample {
    public static void main(String[] args) {
        String jdbcUrl = "jdbc:sqlserver://localhost:1433;databaseName=mydatabase;";
        String username = "myusername";
        String password = "mypassword";

        try {
            // Load the SQL Server JDBC driver
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

            // Establish a connection
            Connection connection = DriverManager.getConnection(jdbcUrl, username, password);

            // Create a statement
            Statement statement = connection.createStatement();

            // Execute a query
            String sql = "SELECT * FROM employees";
            ResultSet resultSet = statement.executeQuery(sql);

            // Retrieve the ResultSetMetaData
            ResultSetMetaData metaData = resultSet.getMetaData();

            // Get column count
            int columnCount = metaData.getColumnCount();
            System.out.println("Column Count: " + columnCount);

            // Iterate over columns
            for (int i = 1; i <= columnCount; i++) {
                String columnName = metaData.getColumnName(i);
                String columnType = metaData.getColumnTypeName(i);
                int columnSize = metaData.getColumnDisplaySize(i);
                System.out.println("Column Name: " + columnName + ", Type: " + columnType + ", Size: " + columnSize);
            }

            // Close the result set, statement, and connection
            resultSet.close();
            statement.close();
            connection.close();
        } catch (ClassNotFoundException e) {
            System.out.println("SQL Server JDBC driver not found");
        } catch (SQLException e) {
            System.out.println("Failed to connect to the database: " + e.getMessage());
        }
    }
}
In the example above, after executing a query and obtaining a ResultSet, we retrieve the ResultSetMetaData object using resultSet.getMetaData(). This provides us with metadata about the columns in the result set.
We can then use various methods of ResultSetMetaData to retrieve column information. For example, getColumnCount() returns the number of columns in the result set. We can iterate over the columns using a loop, and for each column, retrieve details such as the column name (getColumnName()), column type (getColumnTypeName()), and column size (getColumnDisplaySize()).
Please note that the specific methods available in ResultSetMetaData may vary depending on the JDBC driver and database you are using. The example above demonstrates common methods, but you can refer to the JDBC API documentation for a comprehensive list of methods provided by ResultSetMetaData.文章来源地址https://www.toymoban.com/news/detail-498556.html

到了这里,关于利用java.sql包--访问和处理数据库数据的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • sql server 数据库访问端口配置

    1、选择sql server 配置管理器 2、选择SQL Server 网络配置- MSSQLSERVER 的协议 - 右键TCP/IP属性 3、选择IP地址最下面的IPALL 下面的TCP端口 这个端口就是我们访问数据库设置的访问端口,默认端口为1433,如果在不更改的情况下,本地根据IP访问时可不设置端口号,如果更改了,则在访

    2024年02月11日
    浏览(61)
  • Python:利用pymssql模块操作SQL server数据库

    python默认的数据库是 SQLlite,不过它对MySql以及SQL server的支持也可以。这篇文章,介绍下如何在Windows下安装pymssql库并进行连接使用。。。 环境:Windows_64位 版本:python3.6 一、简单介绍 pymssql是一个python的数据库接口,基于FreeTDS构建,对_mssql模块进行了封装,遵循python的DBAP

    2024年02月12日
    浏览(52)
  • Sql server还原失败(数据库正在使用,无法获得对数据库的独占访问权)

    一.Sql server还原失败(数据库正在使用,无法获得对数据库的独占访问权) 本次测试使用数据库实例SqlServer2008r2版 错误详细: 原因分析: 在SqlServer2008r2中在还原数据库时,在执行备份操作的时候,如果有正在访问的用户或者没有关闭的数据库链接,则还原失败。 二、解决方案

    2024年02月13日
    浏览(62)
  • 公网远程访问局域网SQL Server数据库

    数据库的重要性相信大家都有所了解,作为各种数据的电子资料夹,其中可能包含了各种信息,从企业员工信息到网站访问或成交数据无所不包,甚至在某些场景下,数据库已经成为企业正常运行必不可少的条件之一。与企业的其他工作一样,数据库也需要进行必要的维护。

    2024年02月11日
    浏览(48)
  • SQL server设置用户只能访问特定数据库、访问特定表或视图

    在实际业务场景我们可能需要开放单独用户给第三方使用,并且不想让第三方看到与业务不相关的表或视图,我们需要在数据库中设置一切权限来实现此功能: 1.创建用户名 选择默认数据库 服务器角色默认为public 用户映射选择指定数据库 打开需要开放权限的数据库,这里我

    2023年04月09日
    浏览(78)
  • Excel 2019访问SQL Server数据库的实现过程

    源之:https://vip.kingdee.com/article/288066926977041920?productLineId=11 在日常ERP系统实施过程中,往往会遇到客户的一些个性化需求,比如有些客户习惯用Excel电子表格来查看ERP系统中的数据,业余拓展学习了一下,借助ODBC可以实现这个需求。 一、ODBC数据管理和SQL数据库之间的连接的建

    2024年02月11日
    浏览(60)
  • 数据库连接与访问(SQL server与VS2022)

    不同开发工具(开发语言)对数据链接访问的方法是不同的,本次实验主要通过VS2022中的数据工具连接SQL数据库,并通过执行相关代码对数据库中的数据进行处理,实现对窗口进行的系统主界面操作和按键控制操作。 1.首先连接到服务器,要注意登录的是sa账号  2.前期准备工

    2024年02月12日
    浏览(57)
  • PL/SQL+cpolar公网访问内网Oracle数据库

    Oracle,是甲骨文公司的一款关系数据库管理系统,它在数据库领域一直处于领先地位。可以说Oracle数据库系统是世界上流行的关系数据库管理系统,系统可移植性好、使用方便、功能强,适用于各类大、中、小微机环境。它是一种高效率的、可靠性好的、适应高吞吐量的数据

    2024年02月08日
    浏览(42)
  • Python 通过pymssql访问查询操作 SQL Server数据库

    在企业应用开发中,经常用到应用程序访问数据库的开发模式,中小企业使用的数据库中,以ms SQL Server居多。本文就以一个简单的实例模型,简单介绍一下python访问ms sql sever数据库的方法。 本文中以下面的本地SQL Server数据库为例进行数据库连接,数据表的查询、增加、删除

    2024年02月10日
    浏览(106)
  • 【数据库】Sql Server数据迁移,处理自增字段赋值

    给自己一个目标,然后坚持一段时间,总会有收获和感悟! 在实际项目开发中,如果遇到高版本导入到低版本,或者低版本转高版本,那么就会出现版本不兼容无法导入,此时通过程序遍历创建表和添加数据方式可以解决 在 SQL Server 中,数据迁移是常见的场景之一。 以下是

    2024年02月08日
    浏览(56)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包