JDBC使用占位符的插入语句插入不成功是什么原因
……
public static void insert(String name,String password) throws Exception{

          Connection conn = null;
          PreparedStatement st = null;
          ResultSet rs =null;
          conn = DbUtils.getConn();
        String sql="insert into User(name,password) values(?,?)";
        st = conn.prepareStatement(sql);

        st.setString(1,name);
        st.setString(2, password);
        int num = st.executeUpdate(sql);
                    if(num>0){
                     System.out.println("插入成功!!");
             }


                   DbUtils.release(conn, st, rs);
    }

        public static void main(String args[]) throws Exception{
    …… 
        IUserDao.insert("hello","89790");
    …… 
    }

}

+----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| userID | int(11) | YES | | NULL | |
| name | varchar(255) | YES | | NULL | |
| sex | varchar(255) | YES | | NULL | |
| birthday | date | YES | | NULL | |
| password | varchar(255) | YES | | NULL | |
+----------+--------------+------+-----+---------+-------+
一直报错,但是不知道是怎么错了。求教 orz
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?,?)' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.Util.getInstance(Util.java:387)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:939)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3878)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3814)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2478)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2625)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2547)
at com.mysql.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1541)
at com.mysql.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2605)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1469)
at dao.IUserDao.insert(IUserDao.java:107)
at dao.IUserDao.main(IUserDao.java:120)

表名没错,id不是自增的,没有primarykey。把sql写死是可以插入的,用“?”就不行了,为什么呢?

0

3个回答

看看错误信息:
【You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?,?)' at line 1】
sql的语法错误了

st = conn.prepareStatement(sql);
这个已经将sql语句设置了

    st.setString(1,name);
    st.setString(2, password);

** int num = st.executeUpdate(sql);**
你这里就不要这个sql的参数了,不然认为你是按照sql中有值的方式不是占位符的方式来执行

int num = st.executeUpdate(sql);
改为
int num = st.executeUpdate();

2
qq_34573155
qq_34573155 原来如此!O(∩_∩)O谢谢
3 年多之前 回复

user是关键字,需要转义

0
qq_34573155
qq_34573155 回复qq_34573155: \' user\'
3 年多之前 回复
qq_34573155
qq_34573155 回复qq_34573155: 没有经过转义的查找方法也没出现问题
3 年多之前 回复
qq_34573155
qq_34573155 insert into user (name,password) values(?,?) 这样? 但好像还是没有解决。貌似不是这里的问题,而且没有转义过
3 年多之前 回复

我就想知道你的preparedstatement属于哪个包的?
是java.sql包下的吗?

0
qq_34573155
qq_34573155 是的。
3 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
插入语句不成功
我用的是acces,在“插入”按钮的事件中:rnrntransaction trans_customerrntrans_customer =create transactionrnconnect;rnrnINSERT INTO table1 rn ( id1, rn id2, rn id3, rn id4, rn id5, rn id6 ) rn VALUES ( 7, rn 'sle_2.text', rn 'sle_3.text', rn 'sle_4.text', rn 'sle_5.text', rn 'sle_6.text' );rn rncommit using trans_customer;rnrnif trans_customer.sqlcode=0 then rn messagebox('数据库','提交成功')rn else rn messagebox('数据库','提交失败'+trans_customer.sqlerrtext) rn rollback ;rn Return rnend ifrnrn在application的open事件中我是这样写的:rnSQLCA.DBMS = "ODBC"rnSQLCA.AutoCommit = TruernSQLCA.DBParm = "Connectstring='DSN=access'"(这是粘贴过来的)rnconnect;rnrnopen(w_main)rnrn////////////////////////////////////////////////rn点击“插入”按钮系统提示错误,transaction not connected!rn请问在哪里connect啊,我在写在application的open事件中不可以吗?rnrnrn
jdbc 初始化及插入语句
public class initDB { static String url = "jdbc:mysql://localhost:3306/news?useUnicode=true&characterEncoding=gbk" ; //news代表本地创建好的表 ?useUnicode=true&characterEncoding=gbk设置输入流的编码,否则输入数据库的字符串会成乱码 st
JDBC 数据库插入语句
我有一个语句请大家帮我看看,我这里没连数据库 所以验证不了结果rnrnString sql="INSERT INTO Homework_hand_in(hand_in_path) VALUES(way)";rnrn我这里的way是一个string的字符串,请问 values可以这样用么
请教netbeans5.5中,使用sqlserver插入语句不成功的原因
winxp +mssqlserver+sp4 +netbeans5.5rnrn系统中C:\Program Files\Microsoft SQL Server 2000 Driver for JDBC\lib下有文件:rnmsbase.jar 281kbrnmssqlserver.jar 66kbrnmsutil.jar 58kbrnrnnetbeans5.5 库管理器----新建库(MsSql2000)----添加JAR/文件夹(将上面三文件加入)rn单击确定后,重启计算机;rn然后,在程序文件中有代码(其中:jtf1,jtf2,jtf3为三个JTextField)rnrn tryrn Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");rn Connection con=null;rn con=java.sql.DriverManager.getConnection("jdbc:microsoft:sqlserver://localhsot:1433;User=sa;Password=aa1?;DatabaseName=123");rn Statement stmt=con.createStatement();rn String sql="insert into testinfo values('"+jtf1.getText().toString()+"','"+jtf2.getText().toString()+"','"+jtf3.getText().toString()+"')";rn int j = stmt.executeUpdate(sql);rn rn rnrn运行后,库表中并没有写入数据,请教为何????????????????????????????????????
python 操作数据库插入语句占位符问题
1,在 Python 中使用 sqlite3 连接数据库,插入语句的展位符为 "?" cur.execute("insert into user values(?,?,?)",(1,2,"zhang"))2、在 Python 中,使用 pymysql 连接 mysql 数据库,插入语句的占位符为 "%s" cursor.execute("insert into user values(%s
JDBC基本语句插入、查询
//定义驱动程序 private String demo = “com.mysql.jdbc.Driver”; //定义url;jdbc是协议;mysql数据库系统管理名称,localhost:3306本地数据库端口,test为数据库名 private String url = “jdbc:mysql://localhost:3306/test?” + “useUnicode=true&c...
插入数据库表不成功的原因可能有哪些?
这是一个面试题。谢谢!
JAVA 使用插入语句插入记录
最近在做一个数据脱敏(敏感信息脱敏)的项目,遇到这么一个SQL问题,拿出来和大家分享一下。关系型数据库,系统插入数据是使用SQL语句进行批量插入,当插入的数据的字段非常长的时候,里面包含的字符可能会造成SQL语法错误,当时检查了好久,发现了一下几点错误。 1.有些表的字段包括序列化后的内容,包含数据库表结构的序列化内容,如default:('0'),这样的字段值,但是这样执行SQL语句是会报错的
VC6插入语句执行不成功的困惑
函数源码定义如下:rnrn//参数值对入库插入临时表rnbool CDB::InsertParamValue(const LPNS_DBR pDbData)//参数数据入库rnrn if(!IsOpen())rn rn WriteLine("未连接数据库,不能保存参数数据"); rn return false;rn rn CString sql;rn TRYrn rn m_pDB->BeginTrans();rn LPPARAMVALUE p=pDbData->pParamValue;rn for(int i=0;iparaCount;i++)rn rn sql.Format("insert into cl_devicepara_temp(deviceid,qn,cn,oldqn,para_name,para_value)values('%s','%s','%s','%s','%s','%s')",rn pDbData->MN,pDbData->QN,pDbData->CN,pDbData->OLDQN,p->paraName,p->paraValue);rn m_pDB->ExecuteSQL(sql);rn WriteLine(sql);rn p++;rn Sleep(1000);rn rn m_pDB->CommitTrans();rn return true;rn rn CATCH(CDBException, dbe)rn rn CString s="过程:InsertNsDBR插入参数信息到数据库出现异常:"+dbe->m_strError;rn WriteLine(s);rn WriteLine("对应SQL语句为:\n"+sql);rn if((m_nErrorLevel=GetDBExceptionErrorLevel(dbe))==ERROR_FATAL)rn rn s="该错误为致命的错误,数据库关闭";rn WriteLine(s);rn TRACE(s+"\n");rn this->CloseDB();rn rn return false;rn rn END_CATCHrn rnrnrn数据库是ORACLE9I,操作系统:windows2003rn变量:m_pDB是一个MFC ODBC的数据库类CDatabasern现象:执行sql语句没有报告错误、异常,设置了断点,单步调试时执行SQL语句能成功,但是没有设置断点时运行就是不行,数据库表里怎么也没有插入的记录,一般每次插入的记录数量是3-5条记录,一个月也不会执行几次这个函数的。rn这个现象请教大家,可能什么原因引起的?
插入新元素不成功
rn如上代码是我用js创建一个按钮并插入到原来的html中,这样是成功的,但是当把onload事件去掉之后也就是rn rn这样就不行了,请问为什么?非常感谢~
proc++ 数据插入不成功!!!!!!!!!!!!!
我的数据库只定义了两个字段name和sex,编译和执行都没有问题,就是再看数据库中对应的表中没有值!请大家帮忙!!!!!rnrn代码如下:rn#include rn#include rn#include rn#include rn rnrnEXEC SQL INCLUDE sqlca; rnEXEC SQL INCLUDE oraca; rnrnEXEC ORACLE OPTION(ORACA=YES); rnvoid connect();rnvoid insert();rnvoid disconnect();rnrnint main() rn rn EXEC SQL WHENEVER SQLERROR do sql_error("Oracle错误--\n"); rn connect();rn insert();rn disconnect();rn getch(); rn return 0; rnrnrnvoid sql_error(char *msg) rn rn char err_msg[128]; rn size_t buf_len,msg_len; rn rn EXEC SQL WHENEVER SQLERROR continue; rn printf("\n%s\n",msg); rn buf_len=sizeof(err_msg); rn sqlglm(err_msg,&buf_len,&msg_len); rn printf("%.*s", msg_len, err_msg); rn EXEC SQL ROLLBACK RELEASE ; rn exit(EXIT_FAILURE); rnrnrnvoid connect() rn rn EXEC SQL BEGIN DECLARE SECTION; rn VARCHAR username[10],password[10],server[10]; rn EXEC SQL END DECLARE SECTION; rn rn// printf("\n Please enter the name of the user:\n"); rn// gets(username.arr); rn// username.len=(unsigned short)strlen((char*)username.arr); rn// rn// printf("\n Please enter the password:\n"); rn// gets(password.arr); rn// password.len=(unsigned short)strlen((char*)password.arr); rn// rn// printf("\n Please enter the name of the server:\n"); rn// gets(server.arr); rn// server.len=(unsigned short)strlen((char*)server.arr); rn rn strcpy(username.arr, "system");rn username.len=strlen(username.arr);rn strcpy(password.arr, "orcl123");rn password.len=strlen(password.arr);rn strcpy(server.arr, "orcl");rn server.len=strlen(server.arr);rnrn EXEC SQL CONNECT : username IDENTIFIED BY :password using :server; rn printf("\n %s connect %s successfully ! \n",username.arr,server.arr); rn rnrnvoid disconnect() rn rn char temp; rn printf("\n disconnect? (Y/N)"); rn scanf("%c",&temp); rn fflush(stdin); rn rn if(temp!='Y'&&temp!='y') rn rn EXEC SQL COMMIT WORK;rn EXEC SQL ROLLBACK WORK RELEASE; rn printf("\n Donn't commit the order and disconnect !\n\n"); rn rn else rn rn EXEC SQL COMMIT WORK RELEASE; rn printf("\n Commit the order and disconnect !\n\n"); rn exit(1); rn rnrnrnvoid insert() rn rn EXEC SQL INSERT INTO ORCL.emp VALUES('eee','30'); rn rn
一条SQL语句,老是插入不成功,请教!!
以前用oledbparmater代入参数,现在参数较少。想直接写,没想到不行了。rn代码如下:rnpublic void MemberAdd(string userName,string userPassword,string nickName,bool isLock)rn rn string SqlText = "insert into Member(username,password) values('" + userName + "','" + userPassword + "','" + nickName + "','" + isLock + "')";rn HttpContext.Current.Response.Write(SqlText);rn //DB.ExecuteNonQuery(SqlText);rn rn rn提示:Inster into 语句错误,rnResponse.Write输出的语句为:insert into Member(username,password) values('张三','123456','管理员','False') rnrn搞了一个小时,真头大了!!
请教:插入图片资源不成功!
rnMFC中按照:插入\资源(CTRL+I)\导入的步骤插入BMP图片,不成功,现实错误信息"The bitmap has been imported correctly,however because it contains more than 256 colors it cannot be loaded in the bitmap editor."请问怎么解决啊?rnrn rn
插入数据库总是不成功。。
[code=java]class DataBaseInsertrnrn private Connection conn;rn private PreparedStatement ps = null;rnrn DataBaseInsert()rn rn String driver = "com.mysql.jdbc.Driver";rn String user = "root";rn String password = "88888";rn String url = "jdbc:mysql://127.0.0.1:3306/classicmodels";rnrn tryrn rn Class.forName(driver).newInstance();rn conn = DriverManager.getConnection(url, user,rn password);rn conn.setAutoCommit(false);rn rn catch (Exception e)rn rn e.printStackTrace();rn rn rnrn void Insert(Controller controller)rn rn tryrn rn ps = conn.prepareStatement("insert into gamer(score) values (?)");rn ps.setInt(1, controller.getScore());rn ps.executeUpdate();rn rn catch (Exception e)rn rn e.printStackTrace();rn rn rnrn void Close()rn rn // 关闭声明rn if (ps != null)rn rn tryrn rn ps.close();rn rn catch (SQLException e)rn rn e.printStackTrace();rn rn rnrn // 关闭链接对象rn if (conn != null)rn rn tryrn rn conn.close();rn rn catch (SQLException e)rn rn e.printStackTrace();rn rn rn rn[/code]rnrn能够运行,在数据库里的主键也能够自增,但是总是不能把score插入进去。请问哪里有问题吗???
存储过程插入简单记录,插入不成功
CREATE OR REPLACE PROCEDURE testProcedure ASrnBEGINrninsert into test values(1);rnCOMMIT;rnEND;rnrntest表就是一个TOTAL_NUMBER字段的number类型
为什么有时会插入成功,有时插入不成功
INSERT INTO error_tablern (sErrorUser, sErrorService, sErrorContent)rnVALUES ('0752888', 'ZL', '[Microsoft][ODBC SQL Server Driver][SQL Server]第 1 行: ' ada ' 附近有语法错误。'rnrn如果插入里面出现了"'"号怎么办呀!rn
邮箱发送不成功的原因是什么
asp.net 同样的代码一个邮箱不能发送,一个可以发送rn这个是怎么回事rnrn System.Net.Mail.MailMessage myMail = new System.Net.Mail.MailMessage();rn // myMail = new System.Net.Mail.MailMessage("jyyrwy@126.com", "jyyrwy@126.com,cjm198312@163.com");rn myMail = new System.Net.Mail.MailMessage("xmran@126.com", "5593081wpj@163.com");rn myMail.Subject = "5593081wpj net send mail with fujian1111111111111111111111";rn myMail.Body = "5593081wpj net content";rn //System.Net.Mail.Attachment myAttachment = new System.Net.Mail.Attachment("C:/test.txt", System.Net.Mime.MediaTypeNames.Application.Octet);rn // myMail.Attachments.Add(myAttachment);rnrn System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp.126.com", 25);rn client.Credentials = new System.Net.NetworkCredential("xmran", "xmran126");rn client.Send(myMail);rnrn这个不可以发送rnrnSystem.Net.Mail.MailMessage myMail = new System.Net.Mail.MailMessage();rn // myMail = new System.Net.Mail.MailMessage("jyyrwy@126.com", "jyyrwy@126.com,cjm198312@163.com");rn myMail = new System.Net.Mail.MailMessage("jyyrwy@126.com", "5593081wpj@163.com");rn myMail.Subject = "5593081wpj net send mail with fujian1111111111111111111111";rn myMail.Body = "5593081wpj net content";rn //System.Net.Mail.Attachment myAttachment = new System.Net.Mail.Attachment("C:/test.txt", System.Net.Mime.MediaTypeNames.Application.Octet);rn // myMail.Attachments.Add(myAttachment);rnrn System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp.126.com", 25);rn client.Credentials = new System.Net.NetworkCredential("jyyrwy", "a38792");rn client.Send(myMail);rnrnrn这个可以发送rn我很无语rn用户名和密码没有问题。
导出不成功是什么原因?
[code=SQL]rn--有下面的表结构在Sql2008中,在Sql2005中也有相同rn--的表结构,我想从2008导出到2005中,用SQL语句导出不成功呢?rn--我用的是2008的导入导出工具rnCREATE TABLE [dbo].[Soft_SaveFiles]rn(rn [FilesId] [int] IDENTITY(1,1) NOT NULL,rn [FileName] [varchar](220) NOT NULL,rn FilestyleID INT NOT NULL,rn [Files] [image] NULL ---存储小于2M的文档rnrn/*rn我用的是语句导出rnSELECT [FILENAME],FILES FROM Soft_SaveFiles WHERE FileStyleid=8rn错误如下:rn已获得 OLE DB 记录。源:“Microsoft OLE DB Provider for SQL Server” Hresult: 0x80004005 说明:“不能将值 NULL 插入列 'FilesId',表 'MyInfo.dbo.查询';列不允许有空值。INSERT 失败。”。rn (SQL Server 导入和导出向导)rnrn*/rn[/code]
oracle插入语句是报错:missing into keyword是什么原因?
[code=SQL]insert office_supplies_formbaseinfo(boinsid,form_no,applicant_pserson,applicant_department)rnvalues('00-5N3SSH32-E7JN-KORU-DWCB-SPGHQJFVP76D&TaskId=119415','20120215dept','某某','中国移动通信集团公司')[/code]rn运行的时候。按f8首先出来:变量,taskid的对话框,然后输入值,确定。就报错了missing into keyword这个是什么原因?
这个插入语句出现错误,一般是什么原因
一个程序跑起来,不断的执行,有时能完全正确的执行完毕,有时候出现下列错误而中止。请教一下各位,出现下列错误一般是由于什么原因而致:rnrn源程序语句:rninsert into southnorth_billlog (localnet_abbr,process_date,filename,flag)rn values(:slocalnet,:sdirdate,:file,:c_flag);rnrn错误信息:rnSQLSTATE: IX000rnSQLCODE: -271rnrnEXCEPTIONS: Number=2 More? Nrn- - - - - - - - - - - - - - - - - - - -rnEXCEPTION 1: SQLSTATE=IX000rnMESSAGE TEXT: Could not insert new row into the table.rnCLASS ORIGIN: IXrnSUBCLASS ORIGIN: IX000rn- - - - - - - - - - - - - - - - - - - -rnEXCEPTION 2: SQLSTATE=IX000rnMESSAGE TEXT: ISAM error: no more locksrnCLASS ORIGIN: IXrnSUBCLASS ORIGIN: IX000
ie6无法显示插入页是什么原因呢?
ie6无法显示插入页是什么原因呢?打开网页,链接,下载都正常,可是只要是插入页就不无法显示,rn比如新浪网上的滚动新闻就不能显示,rn新浪网上现在缺了好几块!rn其他网站上也是插入页面无法显示!
mysql插入记录报错,请问是什么原因
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '08022394106','PM000064' ,'0187-25', 'HDMI - micro HDMI (2.5M) ', '1', '福田 ' at line 1rnrn请问这是什么原因报错的啊,我是导入一个txt文件,就这一记录报错。
oracle 不能插入值,请问是什么原因
rnSQL> desc timmyrn 名称 是否为空? 类型rn ----------------------------------------- -------- ----------------------------rnrn ID NOT NULL NUMBER(10)rn NAME NOT NULL VARCHAR2(10)rnrnrnrnSQL> insert into timmy values(2,"sad");rninsert into timmy values(2,"sad")rn *rnERROR 位于第 1 行:rnORA-00984: 列在此处不允许rn=====================================================================================rn各位兄弟请帮帮忙吧,都急死了 ,这么都看不出错误rnrn
mysql插入耗时长是什么原因
SQL语句为INSERT INTO test (test1, test2,test3) VALUES ('000000000000000000000000000000000000000000000002', '323','11111')rn使用的方法为MySqlCommand mysqlcom = new MySqlCommand(sqlstr, mysqlcon);rn MySqlDataReader reader = mysqlcom.ExecuteReader();在这句耗时200毫秒
数据插入时报这样的错是什么原因?
代码如下:rn public void SendPhoto(string buildingName, string imgPath, bool type,int bId)rn rn string sqlString;rn string connString = Framework.GlobalModule.MainConnectionString;rn SqlConnection conn = new SqlConnection(connString);rn conn.Open();rn sqlString = "insert into buildingbookflash(BuildingName,Type,Img,Bid) values (buildingName,type,imgPath,bId)";rn SqlCommand comm = new SqlCommand(sqlString, conn);rn comm.ExecuteNonQuery();rn conn.Close();rn rn~~~~~~~~~~~~~~~~~rn在comm.ExecuteNonQuery()报错[color=#FF0000]:”在此上下文中不允许使用名称 "buildingName"。有效表达式包括常量、常量表达式和变量(在某些上下文中)。不允许使用列名。“[/color]rn什么回事?谢谢大家先。
Hibernate数据无法插入,是什么原因啊??
今天在对数据库进行操作的时候,无法对数据进行插入。rn以下巍峨映射文件rnrn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rnrnrn下面是插入操作的语句rnShoporder order=new Shoporder();rnorder.setNumber(number);rnorder.setName(request.getParameter("name"));rnorder.setReallyName(request.getParameter("reallyName"));rnorder.setAddress(request.getParameter("address"));rnorder.setTel(request.getParameter("tel"));rnorder.setSetMoney(request.getParameter("setMoney"));rnorder.setPost(request.getParameter("post"));rnorder.setBz(request.getParameter("bz"));rnorder.setSign(Byte.valueOf("0"));;rnorderDao.save(order);//rn请大家帮忙看下原因rnrn编译的时候也没有错误提示,跟中SQL,也没发现原因
mysql的插入语句的条件插入
MySQL的创建表语句:CREATE TABLE `coordination_template_share` ( `id` int(11) NOT NULL AUTO_INCREMENT, `regional_id` int(11) DEFAULT NULL, `org_id` int(11) DEFAULT NULL COMMENT '组织机构id', `depart_id` in
插入语句
2个数据结构一样的表A,BrnID是自增列rn现在要向B中插入A的数据,A中的ID不需要插入,只插入数据。该怎么写?rn字段很多.
jdbc insert语句插入不生效的问题
请问各位大虾,为何我的insert语句不生效呢??rn Class.forName("oracle.jdbc.driver.OracleDriver");rn Connection coon = DriverManager.getConnection(url, user, password);rn CreateSqlHelper sqlHelper = new CreateSqlHelper();rn String sql = sqlHelper.createTableSql();rn Statement stmt = coon.createStatement();rn stmt.addBatch(sql);rn String sql2 = sqlHelper.createInsertSql(this.path,sqlHelper.getTablename(),this.getColCount());rn System.out.println("*********sql2 :"+sql2);rn String[] sql3 = sql2.split(";");rn for(int i = 0 ; i < sql3.length ; i++)rn stmt.addBatch(sql3[i]);rn rn stmt.executeBatch();rn coon.close();rnrn其中stmt.addBatch(sql);sql是建表的sql语句 ,stmt.addBatch(sql3[i]);是逐个添加insert语句,stmt.executeBatch();执行批处理。rn可是表创建成功了,却没有数据导入进来。插入语句也都有输出。都正确。而且整个过程无任何报错。希望高人指点~~~
关于jdbc执行插入语句的问题
小弟在代码段得到的sql语句是insert into userInfo values('赵六','','1987.8.24');rninsert into userInfo values('王五','22','1988.6.25');rninsert into userInfo values('张三','21','1990.5.23');rninsert into userInfo values('李小四','34',' ')rn每一个insert语句后加上了\r\nrnrn然后在代码里执行插入的时候stmt.executeUpdate(sql2);rnrn总是报错:2010-6-9 18:17:53 txtdataimp.SelectFileView jButton4ActionPerformedrn严重: nullrnjava.sql.SQLException: ORA-00911: 无效字符rnrn at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)rn at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331)rn at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288)rn at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:745)rn at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:207)rn at oracle.jdbc.driver.T4CStatement.executeForRows(T4CStatement.java:957)rn at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1170)rn at oracle.jdbc.driver.OracleStatement.doScrollExecuteCommon(OracleStatement.java:4043)rn at oracle.jdbc.driver.OracleStatement.doScrollStmtExecuteQuery(OracleStatement.java:4195)rn at oracle.jdbc.driver.OracleStatement.executeUpdateInternal(OracleStatement.java:1627)rn at oracle.jdbc.driver.OracleStatement.executeUpdate(OracleStatement.java:1588)rn at txtdataimp.SelectFileView.jButton4ActionPerformed(SelectFileView.java:246)rn at txtdataimp.SelectFileView.access$300(SelectFileView.java:35)rn at txtdataimp.SelectFileView$4.actionPerformed(SelectFileView.java:104)rn at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)rn at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)rn at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)rn at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)rn at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)rn at java.awt.Component.processMouseEvent(Component.java:6041)rn at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)rn at java.awt.Component.processEvent(Component.java:5806)rn at java.awt.Container.processEvent(Container.java:2058)rn at java.awt.Component.dispatchEventImpl(Component.java:4413)rn at java.awt.Container.dispatchEventImpl(Container.java:2116)rn at java.awt.Component.dispatchEvent(Component.java:4243)rn at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)rn at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)rn at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)rn at java.awt.Container.dispatchEventImpl(Container.java:2102)rn at java.awt.Window.dispatchEventImpl(Window.java:2440)rn at java.awt.Component.dispatchEvent(Component.java:4243)rn at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)rn at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)rn at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)rn at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)rn at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)rn at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)rn at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)rnrn可是那句sql放在plsql里生效,不知何解,望大虾指导~~~~
JDBC之获取插入语句返回的主键
该获取主键并不是绝对的,也和具体的数据库实现的驱动有关。 package cn.itcast.jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement
jdbc 批量插入数据不能插入
rt,我一次次的插入是没有问题的,但是批量插入就不能插入,控制台也没有报错,但就是不能成功写到数据库中。高手指点下,下面是代码:rnrnpublic class OracleTMobileDao implements TMobileDao rnpublic long addMobilesBatch(String mobile_Number, String mobile_Type,rn String Card_Number, String is_Available,long total)rn rn long rs = 0;rn Card_Number = "0000000000000";//将card_number的值写成固定的值。rn Connection conn = OracleDaoFactory.getConnection();rn String mobile_Num = mobile_Number;rn try rn conn.setAutoCommit(false);rn String sql = "insert into TMobile values(?,?,?,?)";rn PreparedStatement stmt = conn.prepareStatement(sql);rn long mobile_NumLong =Long.parseLong(mobile_Number);rn for(long i=0;i
JDBC与java插入操作!
大哥们请帮我改一下代码,我的意图是想把mail.txt的内容(里面全部都是邮件地址),全部存在数据库里面,我的数据库就只有一列!但是现在我不知道该怎么去写这个插入操作rnrnimport java.sql.*;rnimport java.io.*;rnpublic class MailGet rn public static void main(String[] args) rn Connection con;rn Statement sql = null;rn ResultSet rs;rn try rn Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");rn catch (ClassNotFoundException e1) rn e1.printStackTrace();rn rn try rn BufferedReader buf = new BufferedReader(new FileReader(rn "F:\\MMMecipse空间\\正则表达式\\src\\mail.txt"));rn String s = "";rn while ((s = buf.readLine()) != null) rn System.out.println(s);rn rn con = DriverManager.getConnection("jdbc:odbc:akqjxx", "", "");rn sql = con.createStatement(); rn sql.executeUpdate("insert into mm(EmailName) values (s)");rn rs = sql.executeQuery("select * from mm");rn while (rs.next()) rn System.out.println("Email:---->" + rs.getString(1));rn rn sql.close();rn catch (SQLException e) rn e.printStackTrace();rn catch (FileNotFoundException e) rn e.printStackTrace();rn catch (IOException e) rn e.printStackTrace();rn rnrn rnrnrn
jdbc插入和更新、查询数据
jdbc java格式化日期
jdbc插入记录
package cn.com.jdbcd;rnrnimport java.sql.Connection;rnimport java.sql.DriverManager;rnimport java.sql.PreparedStatement;rnimport java.sql.ResultSet;rnimport java.sql.SQLException;rnrn/**rn * rn *用单子设计模式连接数据库rn * rn */rnpublic class ConnectionDB rn private static Connection conn = null;rnrn private ConnectionDB() rnrn rn rn public static Connection ConnectionDB()rn if(conn==null)rn try rn Class.forName("oracle.jdbc.driver.OracleDriver");rn String url="jdbc:oracle:thin:@localhost:1521:system";rn String user="scott";rn String password="tiger";rn conn=DriverManager.getConnection(url, user, password);rn System.out.println("数据库连接成功...........");rn catch (ClassNotFoundException e) rn System.out.println("数据库驱动异常:"+e.getMessage());rn e.printStackTrace();rn catch (SQLException e) rn System.out.println("数据库连接异常"+e.getMessage());rn e.printStackTrace();rn rn rn return conn;rn rn rn /**rn * 关闭数据库连接rn */rn rn public static void closeDB(PreparedStatement ps,rn ResultSet rs)rn if(rs!=null)rn try rn rs.close();rn catch (SQLException e) rn System.out.println("关闭数据库异常:"+e.getMessage());rn e.printStackTrace();rn rn if(ps!=null)rn try rn ps.close();rn catch (SQLException e) rn System.out.println("关闭数据库异常2"+e.getMessage());rn e.printStackTrace();rn rn rn rnrn---------------------------------rnpackage cn.com.jdbcd;rnrnimport java.sql.Connection;rnimport java.sql.PreparedStatement;rnimport java.sql.ResultSet;rnimport java.sql.SQLException;rnimport java.util.Scanner;rnrnpublic class TestJdbc1 rnrn /**rn * JDBC连接数据库rn */rnrn private Connection conn = ConnectionDB.ConnectionDB();rnrn private PreparedStatement ps = null;rnrn private ResultSet rs = null;rn rn private int rs1=0;rnrn public static void main(String[] args) rn TestJdbc1 test=new TestJdbc1();rn //Scanner sc=new Scanner(System.in);rn //System.out.print("进行模糊查询,请输入他的姓名中的任意字");rn //test.findInfo();rn //String S=sc.nextLine();rn //test.likeFindInfo(S);rn test.insertInfo(70,"国防部","北京");rn rn /**rn * rn * @param idrn * 插入记录rn * @param locrn */rn private void insertInfo(int id,String name,String loc) rn StringBuffer sql3=new StringBuffer(rn "insert into dept ");rn if(id!=0&&name!=null&&loc!=null)rn sql3.append(" values("+id+",'"+name+"','"+loc+"')");rn rn try rn ps=conn.prepareStatement(sql3.toString());rn System.out.println(sql3.toString());rn //System.out.println("部门号" + "\t" + "姓名 "+"籍贯");rn rn rs1=ps.executeUpdate();rn //System.out.println(rs1);rn while(rs.next())rn System.out.print(rs.getInt("deptno")+"\t");rn System.out.print(rs.getString("dname")+"\t");rn System.out.print(rs.getString("loc")+"\t");rn System.out.println();rn rn catch (SQLException e) rn // TODO Auto-generated catch blockrn e.printStackTrace();rn rn rn /**rn * rn * 模糊查询rn */rn private void likeFindInfo(String name) rn rn /*String sql2="select deptno,dname,loc from " +rn "dept where 1==1";*/rn StringBuffer sql2=new StringBuffer("select * from dept where 1=1");rn rn /*if(id!=0)rn sql2.append(" and deptno like '%");//注意里面的单引号rn sql2.append(id);rn sql2.append("%'");rn */rn if(name!=null)rn sql2.append(" and dname like '%");rn sql2.append(name);rn sql2.append("%'");rn rn try rn ps=conn.prepareStatement(sql2.toString());rn System.out.println(sql2.toString());rn System.out.println("部门号" + "\t" + "姓名 "+"籍贯");rn rs=ps.executeQuery();rn while(rs.next())rn System.out.print(rs.getInt("deptno")+"\t");rn System.out.print(rs.getString("dname")+"\t");rn System.out.print(rs.getString("loc")+"\t");rn System.out.println();rn rn catch (SQLException e) rn System.out.println("查询用户信息报错:"+e.getMessage());rn e.printStackTrace();rn finallyrn ConnectionDB.closeDB(ps, rs);rn rn rn rnrn public void findInfo() rn String sql = "select deptno,dname,loc from dept";rn try rn ps = conn.prepareStatement(sql);rn rs = ps.executeQuery();rn System.out.println("部门号" + "\t" + "姓名 "+"籍贯");rn while (rs.next()) rn System.out.print(rs.getInt(1) + "\t");rn System.out.print(rs.getString(2) + "\t");rn System.out.print(rs.getString(3) + "\t");rn System.out.println();rnrn rn catch (SQLException e) rn System.out.println("查询用户信息报错" + e.getMessage());rn e.printStackTrace();rn finallyrn ConnectionDB.closeDB(ps, rs);rn rn rn rn rnrnrn那个插入业务不能实现啊??rn数据库连接成功...........rninsert into dept values(70,'国防部','北京')rnException in thread "main" java.lang.NullPointerExceptionrn at cn.com.jdbcd.TestJdbc1.insertInfo(TestJdbc1.java:51)rn at cn.com.jdbcd.TestJdbc1.main(TestJdbc1.java:30)rn该怎么解决啊?、谢谢,请帮忙改一下并说明原因
jdbc插入mysql中文乱码的问题
public class Test rnrn public static void main(String[] args) rn Connection conn = null;rn Statement stat = null;rn ResultSet rs = null;rn try rn Class.forName("org.gjt.mm.mysql.Driver").newInstance();rn String connStr = "jdbc:mysql://localhost:3306?useUnicode=true&characterEncoding=UTF-8";rn String dbUser = "root";rn String dbPassword = "123456";rn conn = DriverManager.getConnection(connStr, dbUser, dbPassword);rn if (conn != null) rn System.out.println("连接成功");rn stat = conn.createStatement();rn stat.execute("drop database test_db");rn stat.execute("create database test_db CHARACTER SET UTF8");rn stat.execute("use test_db");rn stat.execute("create table if not exists test_info( role_id int primary key auto_increment, role_name varchar(50) not null)default charset=UTF8");rn stat.execute("insert into test_info(role_name) values ('测试')");rn rs = stat.executeQuery("select * from test_info");rn while (rs.next()) rn System.out.println(rs.getInt("role_id")+" : "+rs.getString("role_name"));rn rn else rn System.out.println("连接失败");rn rn catch (Exception e) rn e.printStackTrace();rn finally rn try rn rs.close();rn stat.close();rn conn.close();rn catch (Exception e2) rn e2.printStackTrace();rn rn rn rnrn麻烦兄弟们看看,为什么上面一段代码查询出来的会是乱码呢?我在数据库中查询也是乱码。我数据库使用的编码是UTF-8的,连接字符串、数据库、表,都是使用的UTF-8。
JDBC插入百万数据
1 long startTime=System.currentTimeMillis(); 2 3 Connection conn=null; 4 try{ 5 conn=getConnection(); 6 conn.setAutoCommit(false); 7
JDBC插入日期问题?
[code=Java]PreparedStatement pstmt = conn.prepareStatement(sql);rnpstmt.setDate(8, new Date());[/code]rn这样写会报错,应该如何获得系统日期插入呢?
jdbc插入返回主键
第一步创建sql 第二步通过connection.prepareStatement(sql,主键) 来创建预编译对象 第三步 为sql中的占位符赋值 第四步,执行sql 第五步获取执行sql的结果 第六步通过ResultSet对象获取返回的主键 public boolean AdvertAdd(Advert ad) throws SQ
jdbc数据库插入问题
用jdbc如何判断你插入的一条记录是否成功呢?用什么好的方法吗?
相关热词 c#异步发送kafka c#窗体编号 c# 操作二进制文件 c# 反射 机制 c#线程 窗体失去响应 c#角度转弧度 c# 解析gps数据 c# vs设置 语法版本 c# json含回车 c#多线程demo