连接数据库jdbc程序

jdbc.properties中的Key--value

/////////////////////////////////

###用户名
username=sa
###密码
password=123456
###连接URL
url=jdbc\:sqlserver\://127.0.0.1\:1433;databse\=stu
###加载驱动
driver=com.microsoft.sqlserver.jdbc.SQLServerDriver


//////////////////////////////////

Connections中的代码

////////////////////////////////

package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ResourceBundle;

public class Connections
{
private static String userName = null;
private static String password = null;
private static String url = null;
private static String driver = null;
private static Connection con = null;

private static void initPramater()
{
   ResourceBundle res =ResourceBundle.getBundle("jdbc");/     /加载资源文件
   userName=res.getString("username");
   password=res.getString("password");
   url=res.getString("url");
   driver=res.getString("driver");
}

public static Connection getConnection()
{
   initPramater();
   try {
    Class.forName(driver);
    con = DriverManager.getConnection(url, userName, password); //获得连接
   } catch (Exception e) {
   
    System.out.println("连接失败");
   }

   return con;
  
}

}


第二种:

<body>
   <%
    Connection con = null;//创建一个边接对象
    String name = request.getParameter("account");//用户名
    String pwd = request.getParameter("password");//密码
    Statement sta = null;//SQL语句对象
    ResultSet rs = null;//结果集
    try {
     Class.forName("com.mysql.jdbc.Driver");//加载驱动
     con = DriverManager.getConnection(
       "jdbc:mysql://localhost:3306/siben", "root", "root"); //获得连接

     sta = con.createStatement();//获得SQL语句对象
     rs = sta.executeQuery("select * from siben where Account='"//执行sql语句,并返回结集
       + name + "' and password='" + pwd + "'");
     if (rs.next()) {//判断是否有结果
      if (rs.getString("account").equals("jonw000")//rs.getString("account")是取值
        && rs.getString("password").equals("000000"))
       out.println("登录成功");
     } else
      out.println("登录失败");
    } catch (Exception e) {
     System.out.println(e.toString());
     out.println("连接失败");
    }
   %>
</body>

你可能感兴趣的:(java,sql,mysql,jdbc,Microsoft)