JDBC---连接SQLserver数据库

本文介绍了使用JDBC连接SQL Server数据库的方法,包括加载驱动、建立连接、执行查询及处理结果等步骤,并提供了Java类文件与JSP文件示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JDBC连接数据库步骤:

      加载驱动程序->打开数据库连接->执行查询->处理查询的结果->清理环境(关闭对象、连接等操作)

JDBC常用接口:

驱动程序接口Driver;驱动程序管理器DriverManager;数据库连接接口Connection;执行SQL语句接口Statement;执行动态SQL语句接口preparedStatement;执行存储过程接口CallableStatement;访问结果集接口ResultSet

注意:

      各个接口的关闭,否则会导致数据库池负重。

      不同数据库的数据库引擎字符串、数据源的字符串区别:

           sql server:如下代码:

           mysql:com.mysql.jdbc.Driver(数据库引擎)          jdbc:mysql://localhost:3306(数据源)


1.Class类文件:

import java.sql.*;

public class ConnectDBTest {

	public static void main(String[] args) {
		String JDriver="com.microsoft.sqlserver.jdbc.SQLServerDriver";     //SQL数据库引擎
		String connectDB="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=practice";    //数据源
		
		try {
			Class.forName(JDriver);//加载数据库引擎,返回给定字符串名的类
		} catch (ClassNotFoundException e) {
			System.out.println("加载数据库引擎失败");
			System.exit(0);
                        //终止程序,System.exit(1)表示异常终止
		}
		System.out.println("数据库驱动成功");
		
		try {
			String user="**";
			String password="***";
			Connection con=DriverManager.getConnection(connectDB,user,password);
                     //连接数据库对象
			System.out.println("连接数据库成功");
	
		     //关闭连接
			stmt.close();
			con.close();
			
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(0);
		}
	}
}

2.JSP文件,可在网页中查看:

区别:内嵌入Java源代码,用<%%>来引入,多段不是用内外嵌套实现的,而是通过顺序连接

<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>数据库连接</title>
</head>
<body>
	<%
	String JDriver="com.microsoft.sqlserver.jdbc.SQLServerDriver";//SQL数据库引擎
	String connectDB="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=practice";//数据源
	
	try {
		Class.forName(JDriver);//加载数据库引擎,返回给定字符串名的类
	} catch (ClassNotFoundException e) {
		out.println("加载数据库引擎失败");
		System.exit(0);//终止程序,System.exit(1)表示异常终止
	}
	out.println("数据库驱动成功");%>
	<br>
	<% 
	
	try {
		String user="**";
		String password="***";
		Connection con=DriverManager.getConnection(connectDB,user,password);//连接数据库对象
		out.println("连接数据库成功");
		Statement stmt=con.createStatement();//创建SQL命令对象


		String query="select * from users";
		ResultSet rs=stmt.executeQuery(query);
		while(rs.next()) {//循环输出每一条记录
			%>
			ID:<%=rs.getInt("id")%><br>
			NAME:<%=rs.getString("username") %><br>
			<% }%>
		<%out.println("读取完毕"); %>
		<%
		//关闭连接
		rs.close();
		stmt.close();
		con.close();
		
	} catch (Exception e) {
		e.printStackTrace();
		System.exit(0);
	}
		%>
</body>
</html>

编程这条路~~~继续加油啦!



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值