I'm a Java developer but I have to develop application in C++.
I just want to read some data from database and set it in this:
struct Line{
char* pdf1;
char* pdf2;
char* ident;
char* reportpath ;
};
and I have this method:
void DBConnect()
{
char* pdf1;
char* pdf2;
SAConnection con;
lines=0;
page[lines] = new Line();
SACommand cmd(&con,"select from pdf where rownum<3 ");
try
{
// connect to database (Oracle in our example)
con.Connect("DB", "user", "password", SA_Oracle_Client);
// Select from our test table
开发者_如何学运维 cmd.Execute();
// fetch results row by row and print results
page[lines]->pdf1="PDF_CM";
page[lines]->pdf2="PDF_LATEST";
lines++;
char *c1=new char(CELLSIZE);
char *c2=new char(CELLSIZE);
while(cmd.FetchNext())
{
page[lines] = new Line();
string s1=cmd.Field("org_doc").asString();
string s2=cmd.Field("rev_doc").asString();
size_t t1=s1.find("text1");
size_t t2=s2.find("text1");
s1.replace(t1,std::string("text1").length(),"text2");
s2.replace(t2,std::string("text1").length(),"text2");
c1=new char(s1.size()+1);
c2=new char(s2.size()+1);
std::copy(s1.begin(), s1.end(), c1);
std::copy(s2.begin(), s2.end(), c2);
c1[s1.size()]='\0';
c2[s2.size()]='\0';
page[lines]->pdf1 =c1;
page[lines]->pdf2 =c2;
s1.erase();
s2.erase();
++lines;
}
con.Commit();
con.Disconnect();
}
catch(SAException &x)
{
try
{
con.Rollback();
}
catch(SAException &)
{
}
printf("%s\n", (const char*)x.ErrText());
}
}
I get an error in the second while loop int this line:
string s1=cmd.Field("org_doc").asString();
But I can't know what the error is because I'm working in plugin :(
Apart from everything else this isn’t proper C++. It’s some mix of C and C++ code.
If you just replace the char*
members with proper std::string
s you will eliminate a whole host of problems (e.g. your erroneous allocation of the char
buffers).
That is, your first step should be to eliminate char*
and new
from your code entirely and use std::string
and automatic storage instead.
The sql strings look suspicious, shouldn't it be
select * from pdf where rownum<3
The actual sql command might return a table with zero columns which would result in an error, if you tried to access field org_doc
(which wouldn't be present in that case).
Glancing at the docs for SACommand
it seems the SAString
and string
are unrelated types. SACommand
is a MFC style string, which requires you to access the underlying buffer to use it as a string
type object.
If the SAChar type is defined as a regular char you could do something like
string s1 = cmd.Field("org_doc").AsString().GetBuffer(min_length);
精彩评论