在安装完数据库和与eclipse进行连接之后,
我们我们要编写一个java代码确定数据库已链接eclipse
import java.sql.Connection;
import java.sql.DriverManager;
public class Main {
public static void main(String [] args)
{
String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
String dbURL="jdbc:sqlserver://localhost:1433;DatabaseName=Text";
String userName="sa";
String userPwd="20153121";
try
{
Class.forName(driverName);
Connection ConnectiondbConn = DriverManager.getConnection(dbURL,userName,userPwd);
System.out.println("连接数据库成功");
}
catch(Exception e)
{
e.printStackTrace();
System.out.print("连接失败");
}
}
}
<%@ page contentType="text/html; charset=gb2312" pageEncoding="UTF-8"%>
<html>
<head>
<title>用户登录</title>
</head>
<body>
<h2 align="center">用户登录</h2>
<form name="form1" action="login_process.jsp" method="post"
onsubmit="return isValidate(form1)">
<table align="center" border="0">
<tr>
<td>账号:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password">
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="登录"></td>
</tr>
</table>
</form>
</body>
</html>
<%@ page language="java" import="java.sql.*" 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=ISO-8859-1">
<title>登录中</title>
</head>
<body>
<%
request.setCharacterEncoding("UTF-8");
String driverStr = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String connStr = "jdbc:sqlserver://localhost:1433; DatabaseName=user";
String dbusername = "sa";
String dbpassword = "4980";
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
Class.forName(driverStr);
conn = DriverManager.getConnection(connStr, dbusername, dbpassword);
String sql = "select * from login where [username]=? and [password]=?";//定义一个查询语句
stmt = conn.prepareStatement(sql);
String user=(String)request.getParameter("username");
String pass=(String)request.getParameter("password");//取出login.jsp的值
stmt.setString(1, user);
stmt.setString(2, pass);
if(user.equals(""))
{
out.print("<script language='javaScript'> alert('账号为空');</script>");
response.setHeader("refresh", "0;url=login.jsp");
}
else if(pass.equals(""))
{
out.print("<script language='javaScript'> alert('密码为空');</script>");
response.setHeader("refresh", "0;url=login.jsp");
}
rs = stmt.executeQuery();
if(rs.next())
response.sendRedirect("login_success.jsp");
else
{
out.print("<script language='javaScript'> alert('账号或密码错误');</script>");
response.setHeader("refresh", "0;url=login.jsp");
}
stmt.close();
conn.close();
%>
</body>
</html>
运行结果:
错误时: