1连接mysql
//普通调用:
//连接以后进行查询try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/java_blog?user=root&password=");
Statement sql=conn.createStatement();
ResultSet rs=sql.executeQuery("select user_id, username,password from userinfo where username='"+username+"' and password='"+password+"'");
int result_number=0;
int user_id=0;
while(rs.next())
{
user_id=rs.getInt("user_id");
result_number++;
}
) catch(Exception e)
{
out.println("出错啦!"+e);
}
//把连接数据库封装成一个类package ...
/**
*数据库连接包
*/
import java.sql.*;
public class DataBase(){
public Connection conn;
public Statement stmt;
public ResultSet rs = null;
public String sqlstr = "";
public Connection connect(){
try{
//设置MySQL的连接驱动
Class.forName("com.mysql.jdbc.Driver").newInstance();
//设置MySQL的连接语句
String url = "jdbc:mysql://localhost:3360/数据库名";
//连接数据库
conn=DriverManager.getConnection(url,"用户名","密码");//一般用户名是root,密码是空,直接引号里边不写东西就行。
stmt=conn.createStatement();
}catch(Exception ee){
System.out.println(ee.tostring());
}
return conn;
}
}
调用数据库类:
DataBase db=new DataBase();
db.connect();
Statement stmt=db.conn.createStatement();
String sql="sql语句";
ResultSet rs=stmt.executeQuery(sql);//用于查询的语句
while(rs.next()){//当返回的结果集有值
//自定义语句
}
rs.close();
2连接sql
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url="jdbc:sqlserver://localhost:50573;DatabaseName=test";
其他同上普通调用一样