安装MySQL真是花费一番力气啊,嘿嘿。
package com.xynu.util;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
public class MySQLCon {
/*
* 写一个函数
*/
public static Connection get() throws SQLException{
// try里面的的访问不到“conn”,需要将conn在外面初始化;
Connection conn=null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/chenlong","root","123456");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
/*
* 插入
*/
public static void insert(String username,String password) throws SQLException{
// 拿到链接
Connection conn= get();
// 返回数据库连接的一个状态
Statement statement=conn.createStatement();
String sql="insert into user( username,password) values('"+username+"','"+password+"')";
statement.execute(sql);
System.out.println("******插入成功*******");
}
public static void main(String[] args) throws SQLException {
Connection conn= get();
if(get()!=null){
System.out.println("******连接成功******");
}else {
System.out.println("error");
}
insert("chenlong2", "4422");
}
}