有谁能指教下
jave 和 mysql 怎么连接,那个大虾赐教下~~~~~~~~~~~~~
------解决方案--------------------import java.sql.*;
public class T1 {
/** *//**
* @param args
*/
public static void main(String[] args) throws
SQLException,
ClassNotFoundException{
// TODO Auto-generated method stub
Class.forName( "com.mysql.jdbc.Driver ");
Connection con = DriverManager.getConnection( "jdbc:mysql://localhost/test ", "feng ", " ");
//Statement st = con.createStatement();
PreparedStatement pst = con.prepareStatement( "select * from course where cid=? ");
//ResultSet rs = st.executeQuery( "select * from course ");
pst.setString(1, "01 ");
ResultSet rs = pst.executeQuery();
while(rs.next()){
System.out.println(rs.getString(2));
}
}
}
------解决方案--------------------首先,你需要到 MySQL 的官方网站:http://dev.mysql.com/downloads/connector/j/5.0.html 去下载最新版本的 MySQL Connector/J,将其中的 mysql-connector-java-5.0.x-bin.jar 文件放到 classpath 中,就可以连接 MySQL 了。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import
java.sql.SQLException;
public class Conn {
public static void main(String[] args){
try {
Class.forName( "com.mysql.jdbc.Driver ");
} catch (Class
NotFoundException e) {
e.printStackTrace();
}
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
String url = "jdbc:mysql://localhost:3306/bookstore ";
String username = "root ";
String password = "root ";
con = DriverManager.getConnection(url, username, password);
String sql = "SELECT * FROM book WHERE book_id = ? ";
ps = con.prepareStatement(sql);
ps.setInt(1, 1);
rs = ps.executeQuery();
while(rs.next()){
...
}
}catch(SQLException sqle){
sqle.printStackTrace();
}finally {
try {
rs.close();
ps.close();
con.close();
}catch(SQLException sqle){
sqle.printStackTrace();
}
}
}
}
------解决方案--------------------Class.forName( "com.mysql.jdbc.Driver ");
Connection con = DriverManager.getConnection( "jdbc:mysql://localhost/dbname ", "dbuser ", "dbpwd ");
------解决方案--------------------为什么不行?要把数据库名、用户名和密码都改成你的,出现异常吗?若出现异常,可以将异常贴上来让大家看看。