package com.mysql;
import java.sql.*;
public class mysql_test {
/**
* @param args
*/
//JDBC DRIVER and DB
static final String DRIVER="com.mysql.jdbc.Driver";
static final String DB="jdbc:mysql://localhost/test";
static final String USER="root";
static final String PASSWD="hadoop";
public static void main(String[] args) {
// TODO Auto-generated method stub
Connection conn=null;
Statement stmt=null;
try {
//加载驱动程序
Class.forName(DRIVER);
System.out.println("Connecting to a selected database...");
//打开一个连接
conn=DriverManager.getConnection(DB, USER, PASSWD);
//执行一个查询
stmt=conn.createStatement();
String sql="insert into student values('scofield',45,89,100)";
stmt.executeUpdate(sql);
System.out.println("Inserting records into the table successfully!");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
if(stmt!=null)
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(conn!=null)
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
本文展示了一个使用Java和JDBC进行MySQL数据库插入操作的示例代码。通过加载驱动、建立连接、执行SQL插入语句并关闭资源,成功地将记录插入到指定的数据库表中。
4725

被折叠的 条评论
为什么被折叠?



