java数据库编程
java连接数据库
创建lib文件夹并导入mysql驱动jar包
加载驱动
Class.forName("com.mysql.jdbc.Driver");
获取连接对象
private static String url
= "jdbc:mysql:///wtu?useUnicode=true&characterEncoding=utf-8";
private static String userName
= "root";
private static String password
= "root";
private static Connection con
;
con
= DriverManager
.getConnection(url
,userName
,password
);
获取执行对象
//获取静态执行对象
Statement stmt = conn.createStatement();
//获取动态执行对象
String sql="..."
PreparedStatement pstmt = conn.prepareStatement(sql);
执行sql语句
pstmt
.executeUpadte()
pstmt
.executeQuary()
补充JDBC2.0批处理
package jdbc2batchprocessing
;
import utils
.JdbcUtils
;
import java
.sql
.Connection
;
import java
.sql
.PreparedStatement
;
import java
.sql
.Timestamp
;
public class BatchProcessingTest {
public static void main(String
[] args
) throws Exception
{
Connection conn
= JdbcUtils
.getConn();
String sql
= "INSERT INTO test VALUES(?,?,?,?,?)";
PreparedStatement pstmt
= conn
.prepareStatement(sql
);
int num
= 130,age
=32;
for (int i
= 0; i
< 8; i
++) {
pstmt
.setString(1,String
.valueOf(num
));
pstmt
.setString(2,"李兴华"+i
);
pstmt
.setInt(3,age
);
pstmt
.setString(4,"女");
pstmt
.setTimestamp(5,new Timestamp(new java.util.Date().getTime()));
pstmt
.addBatch();
num
++;
age
++;
}
int[] temps
= pstmt
.executeBatch();
System
.out
.println("更新了"+temps
.length
+"条数据");
pstmt
.close();
conn
.close();
}
}
结果集元数据MetaData
package metadata
;
import utils
.JdbcUtils
;
import java
.sql
.Connection
;
import java
.sql
.PreparedStatement
;
import java
.sql
.ResultSet
;
import java
.sql
.ResultSetMetaData
;
public class ResultMetaDataTest {
public static void main(String
[] args
) throws Exception
{
Connection conn
= JdbcUtils
.getConn();
String sql
= "SELECT * FROM test WHERE num=107";
PreparedStatement pstmt
= conn
.prepareStatement(sql
);
ResultSet rs
= pstmt
.executeQuery();
ResultSetMetaData md
= rs
.getMetaData();
int count
= md
.getColumnCount();
while (rs
.next()){
for (int i
=1;i
<=count
;i
++){
Object value
= rs
.getObject(i
);
String columnName
= md
.getColumnName(i
);
System
.out
.println(columnName
+":"+value
);
}
}
rs
.close();
pstmt
.close();
conn
.close();
}
}