IDEA使用JDBC连接Sqlserver数据库
在IDEA的项目中添加对应数据库的jar包
在项目中创建util包和DBUtil类用来存放数据库连接的java代码。
完整代码
package com.hnpi.util;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;public class DBUtil {public static Connection getConn(){String url = "jdbc:sqlserver://localhost:1433;databaseName=Manager"; //databaseName=数据库名称String user = "sa"; //数据库用户名String pwd = "1"; //数据库密码Connection conn = null;//创建链接try {Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");conn = DriverManager.getConnection(url, user, pwd);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}return conn;}//关闭连接public static void closeConn(Connection conn, PreparedStatement ps, ResultSet rs){if(conn!=null){try {conn.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(ps!=null){try {ps.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(rs!=null){try {rs.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}