[java]代码库
package mysql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class TestConnect {
public static void main(String[] args) {
Connection con = null;
//1.加载数据库驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("加载失败!");
e.printStackTrace();
}
System.out.println("加载成功!");
//2.连接数据库
try {
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/db_library", "root", "123");
} catch (SQLException e) {
System.out.println("连接数据库失败!");
e.printStackTrace();
}
System.out.println("成功连接数据库!");
//3.执行sql语句语句的statement,然后执行sql语句
/*sql创建表语句
*create table table1(id int not null,
*name varchar(20) not null,
*age int not null,
*primary key(id));
*/
try {
Statement statement = con.createStatement();
int i=statement.executeUpdate("create table table1(id int not null auto_increment,name varchar(20) not null,age int not null,primary key(id))");
//int i=statement.executeUpdate("drop table table1");
System.out.println(i);
System.out.println("建表成功!");
} catch (SQLException e) {
System.out.println("执行sql语句出错!");
e.printStackTrace();
return;
}
System.out.println("执行成功!");
}
}