对mySQL数据库进行数据操作之添加

对mySQL数据库中数据进行添加数据操作


package cn.edu.hpu.operate;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;

public class Add {
	private static  String driver = "com.mysql.jdbc.Driver";
	private static  String url =  "jdbc:mysql://localhost:3306/数据库数据名";
	
	public static Connection getConn()
	{
		Connection conn = null;
		try
		{
			Class.forName(driver);
		}
		catch(ClassNotFoundException e)
		{
			e.printStackTrace();
		}
		try
		{
			conn = (Connection) DriverManager.getConnection(url,"用户名","密码");
			
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
		return conn;
	}
	public static void main(String[] args)
	{
		//插入操作
		int i = 0;
		String sql="insert into student(student 的列属性,用逗号隔开) values(?,?,?,?)";
		Connection cnn = getConn();
		
		try
		{
		
			PreparedStatement preStmt = cnn.prepareStatement(sql);
			
			preStmt.setInt(1,? );
			preStmt.setString(2,?);
			preStmt.setString(3,?);
			preStmt.setInt(4, ?);
			i =i+ preStmt.executeUpdate();
			//问号表示你对应要修改的数据库中的值,注意要是区分是整形还是字符串
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
		System.out.println(i);
	}
}


你可能感兴趣的:(对mySQL数据库进行数据操作之添加)