本文实例讲述了jsp使用jdbc连接mysql数据库的方法。分享给大家供大家参考,具体如下:
1. 可在 http://www.mysql.com/products/connector-j/index.html下载mysql jdbc驱动程序mysql-connector-java-*.jar,如我下载的是mysql-connector-java-5.1.18-bin.jar并加入到classpath下面,或加入到项目中。
2. 注册jdbc驱动程序
try {
class.forname("com.mysql.jdbc.driver");
}
catch(classnotfoundexception e) {
system.out.println("找不到驱动程序");
}
3. 提供jdbc url
jdbc:mysql://主机名:端口号/数据库名?user=***&password=***&useunicode=true&characterencoding=utf8
端口号:mysql的默认值是3306
useunicode,characterencoding:如果要存取中文,则必须使用,表明是否使用unicode,并指定编码方式.
4. 从drivermanager取得connection
可以直接将jdbc url传入drivermanager.getconnection()得到connection对象,如:
try {
string url = "jdbc:mysql://localhost:3306/guestbook?user=root&password=123456";
connection conn = drivermanager.getconnection(url);
if(!conn.isclosed())
system.out.println("数据库连接成功!");
conn.close();
}
catch(sqlexception e) {
....
}
也可以将username和password传入drivermanager.getconnection()得到connection对象,如:
string url = "jdbc:mysql://localhost:3306/addressbook";
string user = "zhujun";
string password = "123456";
connection conn = drivermanager.getconnection(url, user, password);
一个完整的例子:
import java.sql.*;
public class testjdbc {
public static void main(string[] args) throws exception {
class.forname("com.mysql.jdbc.driver");
string url = "jdbc:mysql://localhost:3306/2";
string user = "root";
string password = "19870714";
connection conn = drivermanager.getconnection(url, user, password);
if(!conn.isclosed())
{
system.out.println("success");
}
conn.close();
}
}
希望本文所述对大家jsp程序设计有所帮助。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!