java中连接数据库操作的语句,获得执行sql语句对数据库进行操作

由于在myeclipse中连接数据库操作需要相应的数据库驱动包jar文件,所以在写代码前导入数据库驱动文件.jar文件还是很重要的,我选择的是微软的sql server数据库,所以要事先把jar文件导入到文件中。


下面是我的代码:

package sqlserver;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class mysql {

public static  Connection getConn()
{
String user = "sa";
String password = "123456";
String dbname  = "iERP81";
String url = "jdbc:sqlserver://localhost:1433;databasename = "+dbname;
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
Connection conn = null;
try
{
Class.forName(driverName);
conn = DriverManager.getConnection(url,user,password);



}catch(Exception e)
{
System.out.println("连接失败");


}
return conn;
}

public static void main(String[] args) {

int count = 0;
try {
Statement statement = getConn().createStatement();

String sql = "select * from empleaveapproval ";
ResultSet rs = statement.executeQuery(sql);
while(rs.next())
{
System.out.println(rs.getNString(1));
count++;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("操作失败:!");
e.printStackTrace();
}
System.out.println("总共有"+count+"个数");


}


}

你可能感兴趣的:(java,java中连接数据库操作)