java連接mysql數(shù)據(jù)庫
來源:程序員人生 發(fā)布時間:2015-04-17 08:20:46 閱讀次數(shù):3687次
1、首先下載mysql安裝包,下載鏈接mysql下載,然后安裝。
2、輸入安裝時的用戶名和密碼,連接數(shù)據(jù)庫。
3、在Eclipse 中安裝mysq JDBCl驅(qū)動,安裝步驟以下圖示:



測試是不是成功連接mql,代碼:
package day_09;
import java.sql.*;
public class Test
{
public static void main(String[] args)
{
String url="jdbc:mysql://localhost:3306/mydb";
String user="root";
String password="281889";
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(url,user,password);
stmt=conn.createStatement();
String sql;
sql="insert into student values(2014218,'李月','女')";
stmt.execute(sql);
sql="select * from student";
rs = stmt.executeQuery(sql);
System.out.println("學(xué)號" + " " + " 姓名"+" "+"性別");
String name = null;
while(rs.next())
{
name = rs.getString("sname");
System.out.println(rs.getString("sno") + " " + name+" "+rs.getString("sex"));
}
}
catch(ClassNotFoundException e1)
{
System.out.println("
數(shù)據(jù)庫驅(qū)動不存在!"+e1.toString());
}
catch(SQLException e2)
{
System.out.println("
數(shù)據(jù)庫存在異常"+e2.toString());
}
finally
{
try
{
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(conn!=null)
conn.close();
}
catch(SQLException e)
{
System.out.println(e.toString());
}
}
}
}
打印結(jié)果:

生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機掃描二維碼進行捐贈