Sparql substract instance - sparql

I have an anthology, I created an interface for evaluation or there is a submit button. This button allows you to calculate the difference between the old value and the value 20. I try to select an instance with sparql and I would evaluate an instance subtracts the old value with the value 20.
valider.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Model m=ModelFactory.createMemModelMaker().createModel(null);
FileManager.get().readModel( m, owlFile );
String myOntologyName = "ProjetHela";
String uri="file:///C:/Project/Krs1.owl";
// Définition de prefixe pour simplifier l'utilisation de SPARQL
String reuses = "maj: <"+RDF.getURI()+">" ;
// String myOntologyPrefix = "PREFIX "+myOntologyName+": <"+myOntologyNS+">" ;
String myOntologyPrefix = "PREFIX "+myOntologyName+": <"+uri+">" ;
// if (liste.getSelectedItem().toString().equals("GMP: Puissance=60352 Watt,limite supérieure= 73500 Watt")) {
String queryString=
"PREFIX maj: <http://www.owl-ontologies.com/reuses.owl#>"
+ "SELECT ?hasnameevaluated"
+ " WHERE "
+ "{"
+ "?Besoin maj:hasnameevaluated ?hasnameevaluated "
+"FILTER (?hasnameevaluated - 20) "
+ " } ";
Query query = QueryFactory.create(queryString) ;
QueryExecution qexec = QueryExecutionFactory.create(query, m) ;
try {
ResultSet rs = qexec.execSelect() ;
// Affichage des resultats
for ( ; rs.hasNext() ; ){
//System.out.print("");
QuerySolution rb = rs.nextSolution() ;
String y = rb.getLiteral("hasnameevaluated").getString();
System.out.println( " " + y);
}} finally {
qexec.close() ;
}
}
}
);
but it doesn't work
please help me

FILTER (?hasnameevaluated - 20)
is a test , not an assignment of a value.
Did you mean to use:
BIND (?hasnameevaluated - 20 AS ?newvalue)
or
SELECT ?hasnameevaluated (?hasnameevaluated - 20 AS ?newvalue) WHERE

Related

Is it possible to execute query independently on each partition using colocated computing in IgniteCallable without explicitly joining on keys?

I have one client code which does get all the keys and then call the affinityCall which execute on server-node
Code on client side for computing on each partition
Map<Integer, List<Integer>> partitionMap = new HashMap<>();
for(Integer affKey : affKeys) {
Integer partitionId = affinityFunction.partition(affKey);
partitionMap.computeIfAbsent(partitionId, k -> new ArrayList<>()).add(affKey);
}
Collection<IgniteFuture<Map<Integer, Double>>> futures = new ArrayList<>();
Collection<String> cacheList = new ArrayList<>();
cacheList.add(CACHE_NAME);
for (int partitionId : partitionMap.keySet()) {
IgniteFuture<Map<Integer, Double>> future = compute.affinityCallAsync(cacheList, partitionId,
new Worker(CACHE_NAME, partitionMap.get(partitionId)));
futures.add(future);
}
Code for the worker is
public class Worker implements IgniteCallable<Map<Integer, Double>> {
#IgniteInstanceResource
private Ignite ignite;
private String cacheName;
private List<Integer> keys;
public Worker(String cacheName, List<Integer> keys){
this.cacheName = cacheName;
this.keys = keys;
}
#Override
public Map<Integer, Double> call() throws Exception {
IgniteCache<Object, Object> cache = ignite.cache(cacheName);
SqlFieldsQuery query =
new SqlFieldsQuery("select affKey, sum(count) from Summary s
join table(affKey integer = ?) a
on a.affKey = s.affKey
join table(studyId integer = ?) st
on st.studyId = s.studyId
group by affKey")
.setArgs((Object) keys.toArray());
Map<Integer, Double> result = new HashMap<>();
try (QueryCursor<List<?>> cursor = cache.query(query)) {
for (List<?> record : cursor) {
Integer affKey = (Integer) record.get(0);
Double sum = (Double) record.get(1);
result.put(affKey, sum);
}
}
return result;
}
}
In above case I'm joining on all the keys present in the partition. can anybody help how can we get rid of the extra join here.
More specifically this is query on which I'm working on.
public SqlFieldsQuery getQueryStringForGroup1() {
String queryString = "select g.geneId as geneId, sum(count) as count, " +
"sum(g.rawMean) as sumRawMean, " +
"sum(g.squareRawMean) as sumSquareRawMean, " +
"sum(g.rawSess) as rawSess, " +
"sum(g.mean) as sumMean, " +
"sum(g.squareMean) as sumSquareMean, " +
"sum(g.squareSd) as sEss, " +
"sum(g.greaterThan0) as sumGreaterThan0 " +
"from GeneSummary g " +
"join table(geneId integer = ?1) gn on g.geneId = gn.geneId " +
(filter.getStudyId().isEmpty() ? ""
: "join table(studyId integer = ?4) s on g.studyId = s.studyId ")
+
(filter.getCellType().isEmpty() ? ""
: "join table(cellType integer = ?7) ct on g.cellType = ct.cellType ")
+
(filter.getTissueType().isEmpty() ? ""
: "join table(tissueType integer = ?6) t on g.tissueType = t.tissueType ")
+
(filter.getCondition().isEmpty() ? ""
: "join table(condition integer = ?5) cd on g.condition = cd.condition ")
+
(filter.getAge().isEmpty() ? ""
: "join table(age integer = ?3) a on g.age = a.age ")
+
(filter.getGender().isEmpty() ? ""
: "join table(gender integer = ?2) gd on g.gender = gd.gender ")
+
"group by g.geneId";
SqlFieldsQuery query = new SqlFieldsQuery(queryString).setArgs(
(Object) geneMap.keySet().toArray(),
(Object) filter.getGender().toArray(),
(Object) filter.getAge().toArray(),
(Object) filter.getStudyId().toArray(),
(Object) filter.getCondition().toArray(),
(Object) filter.getTissueType().toArray(),
(Object) filter.getCellType().toArray());
//.setPartitions(this.partitionId);
// query.setPartitions(this.partitionId);
return query;
}
As you mentioned in the comment I modified argument to set for the query.
Modified query looks like this.
public SqlFieldsQuery getQueryStringForGroup1() {
String queryString = "select g.geneId as geneId, sum(count) as count, " +
"sum(g.rawMean) as sumRawMean, " +
"sum(g.squareRawMean) as sumSquareRawMean, " +
"sum(g.rawSess) as rawSess, " +
"sum(g.mean) as sumMean, " +
"sum(g.squareMean) as sumSquareMean, " +
"sum(g.squareSd) as sEss, " +
"sum(g.greaterThan0) as sumGreaterThan0 " +
"from GeneSummary g " +
// "join \"GeneName\".\"GENENAME\" gn on g.geneId = gn.geneId and gn.partitionId
// = ?1 " +
// "join table(geneId integer = ?1) gn on g.geneId = gn.geneId " +
(filter.getStudyId().isEmpty() ? ""
: "join table(studyId integer = ?4) s on g.studyId = s.studyId ")
+
(filter.getCellType().isEmpty() ? ""
: "join table(cellType integer = ?7) ct on g.cellType = ct.cellType ")
+
(filter.getTissueType().isEmpty() ? ""
: "join table(tissueType integer = ?6) t on g.tissueType = t.tissueType ")
+
(filter.getCondition().isEmpty() ? ""
: "join table(condition integer = ?5) cd on g.condition = cd.condition ")
+
(filter.getAge().isEmpty() ? ""
: "join table(age integer = ?3) a on g.age = a.age ")
+
(filter.getGender().isEmpty() ? ""
: "join table(gender integer = ?2) gd on g.gender = gd.gender ")
+
"group by g.geneId";
SqlFieldsQuery query = new SqlFieldsQuery(queryString);
if (!filter.getCellType().isEmpty())
query.setArgs(
(Object) geneMap.keySet().toArray(),
(Object) filter.getGender().toArray(),
(Object) filter.getAge().toArray(),
(Object) filter.getStudyId().toArray(),
(Object) filter.getCondition().toArray(),
(Object) filter.getTissueType().toArray(),
(Object) filter.getCellType().toArray());
if (!filter.getTissueType().isEmpty())
query.setArgs(
(Object) geneMap.keySet().toArray(),
(Object) filter.getGender().toArray(),
(Object) filter.getAge().toArray(),
(Object) filter.getStudyId().toArray(),
(Object) filter.getCondition().toArray(),
(Object) filter.getTissueType().toArray());
if (!filter.getCondition().isEmpty())
query.setArgs(
(Object) geneMap.keySet().toArray(),
(Object) filter.getGender().toArray(),
(Object) filter.getAge().toArray(),
(Object) filter.getStudyId().toArray(),
(Object) filter.getCondition().toArray());
if (!filter.getStudyId().isEmpty())
query.setArgs(
(Object) geneMap.keySet().toArray(),
(Object) filter.getGender().toArray(),
(Object) filter.getAge().toArray(),
(Object) filter.getStudyId().toArray());
if (!filter.getAge().isEmpty())
query.setArgs(
(Object) geneMap.keySet().toArray(),
(Object) filter.getGender().toArray(),
(Object) filter.getAge().toArray());
if (!filter.getGender().isEmpty())
query.setArgs(
(Object) geneMap.keySet().toArray(),
(Object) filter.getGender().toArray());
query.setPartitions(this.partitionId);
return query;
}
Workaround to it was set atleast last argument in the query.
Now my question here is, which approach is better here ?
With join on affinity key or querying on each partition.
With the caveat that I've not studied your query, you can limit a query to a specific partition like this:
var q = new SqlFieldsQuery("select * from table")
.setPartitions(1, 2, 3);

Passing Variables into Dapper are query parameters... "A request to send or receive data was disallowed because the socket is not connected

Ok , I"m doing what looks like a simple Dapper query
but if I pass in my studId parameter, it blows up with this low level networking exception:
{"A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied."}
if I comment out the line of sql that uses it, fix the where clause, ,and comment out the line where it's added the the parameters object. It retrieves rows as expected.
I've spent the last 2.5 days trying everything I could think of, changing the names to match common naming patterns, changing type to a string (just gave a error converting string to number), yadda yadda yadda..
I'm at a complete loss as to why it doesn't like that parameter, I look at other code that works and they pass Id's just fine...
At this point I figure it has to be an ID-10-t that's staring me in the face and I'm just assuming my way right past it with out seeing it.
Any help is appreciated
public List<StudDistLearnSchedRawResponse> GetStudDistanceLearningScheduleRaw( StudDistLearnSchedQueryParam inputs )
{
var aseSqlConnectionString = Configuration.GetConnectionString( "SybaseDBDapper" );
string mainSql = " SELECT " +
" enrollment.stud_id, " +
" sched_start_dt, " +
" sched_end_dt, " +
" code.code_desc, " +
" student_schedule_dl.enrtype_id, " +
" student_schedule_dl.stud_sched_dl_id, " +
" dl_correspond_cd, " +
" course.course_name, " +
" stud_course_sched_dl.sched_hours, " +
" actual_hours, " +
" course_comments as staff_remarks, " + // note this column rename - EWB
" stud_course_sched_dl.sched_item_id , " +
" stud_course_sched_dl.stud_course_sched_dl_id " +
" from stud_course_sched_dl " +
" join student_schedule_dl on student_schedule_dl.stud_sched_dl_id = stud_course_sched_dl.stud_sched_dl_id " +
" join course on stud_course_sched_dl.sched_item_id = course.sched_item_id " +
" left join code on student_schedule_dl.dl_correspond_cd = code.code_id " +
" join enrollment_type on student_schedule_dl.enrtype_id = enrollment_type.enrtype_id " +
" join enrollment on enrollment_type.enr_id = enrollment.enr_id " +
" where enrollment.stud_id = #studId " +
" and sched_start_dt >= #startOfWeek" +
" and sched_end_dt <= #startOfNextWeek";
DapperTools.DapperCustomMapping<StudDistLearnSchedRawResponse>();
//string sql = query.ToString();
DateTime? startOfWeek = StartOfWeek( inputs.weekStartDateTime, DayOfWeek.Monday );
DateTime? startOfNextWeek = StartOfWeek( inputs.weekStartDateTime.Value.AddDays( 7 ) , DayOfWeek.Monday );
try
{
using ( IDbConnection db = new AseConnection( aseSqlConnectionString ) )
{
db.Open();
var arguments = new
{
studId = inputs.StudId, // it chokes and gives a low level networking error - EWB
startOfWeek = startOfWeek.Value.ToShortDateString(),
startOfNextWeek = startOfNextWeek.Value.ToShortDateString(),
};
List<StudDistLearnSchedRawResponse> list = new List<StudDistLearnSchedRawResponse>();
list = db.Query<StudDistLearnSchedRawResponse>( mainSql, arguments ).ToList();
return list;
}
}
catch (Exception ex)
{
Trace.WriteLine(ex.ToString());
return null;
}
}
Here is the input object
public class StudDistLearnSchedQueryParam
{
public Int64 StudId;
public DateTime? weekStartDateTime;
}
Here is the dapper tools object which just abstracts some ugly code to look nicer.
namespace EricSandboxVue.Utilities
{
public interface IDapperTools
{
string ASEConnectionString { get; }
AseConnection _aseconnection { get; }
void ReportSqlError( ILogger DalLog, string sql, Exception errorFound );
void DapperCustomMapping< T >( );
}
public class DapperTools : IDapperTools
{
public readonly string _aseconnectionString;
public string ASEConnectionString => _aseconnectionString;
public AseConnection _aseconnection
{
get
{
return new AseConnection( _aseconnectionString );
}
}
public DapperTools( )
{
_aseconnectionString = Environment.GetEnvironmentVariable( "EIS_ASESQL_CONNECTIONSTRING" );
}
public void ReportSqlError( ILogger DalLog, string sql, Exception errorFound )
{
DalLog.LogError( "Error in Sql" );
DalLog.LogError( errorFound.Message );
//if (env.IsDevelopment())
//{
DalLog.LogError( sql );
//}
throw errorFound;
}
public void DapperCustomMapping< T >( )
{
// custom mapping
var map = new CustomPropertyTypeMap(
typeof( T ),
( type, columnName ) => type.GetProperties( ).FirstOrDefault( prop => GetDescriptionFromAttribute( prop ) == columnName )
);
SqlMapper.SetTypeMap( typeof( T ), map );
}
private string GetDescriptionFromAttribute( System.Reflection.MemberInfo member )
{
if ( member == null ) return null;
var attrib = (Dapper.ColumnAttribute) Attribute.GetCustomAttribute( member, typeof(Dapper.ColumnAttribute), false );
return attrib == null ? null : attrib.Name;
}
}
}
If I change the SQL string building to this(below), but leave everything else the same(Including StudId in the args struct)... it doesn't crash and retrieves rows, so it's clearly about the substitution of #studId...
// " where enrollment.stud_id = #studId " +
" where sched_start_dt >= #startOfWeek" +
" and sched_end_dt <= #startOfNextWeek";
You name your data members wrong. I had no idea starting a variable name with # was possible.
The problem is here:
var arguments = new
{
#studId = inputs.StudId, // it chokes and gives a low level networking error - EWB
#startOfWeek = startOfWeek.Value.ToShortDateString(),
#startOfNextWeek = startOfNextWeek.Value.ToShortDateString(),
};
It should have been:
var arguments = new
{
studId = inputs.StudId, // it chokes and gives a low level networking error - EWB
startOfWeek = startOfWeek.Value.ToShortDateString(),
startOfNextWeek = startOfNextWeek.Value.ToShortDateString(),
};
The # is just a hint to Dapper, that it should replace with a corresponding member name.
## has special meaning in some SQL dialects, that's probably what makes the trouble.
So here's what I Found out.
The Sybase implementation has a hard time with Arguments.
It especially has a hard time with arguments of type int64 (this existed way pre .NetCore)
So If you change the type of the passed in argument from int64 to int32, everything works fine.
You can cast it, or just change the type of the method parameter

Prepare Statement very slow compare with direct query | Oracle DB

I have a prepared statement in my application and it takes 3 minutes to give an results. However, same query i have executed in sql developer and it only takes less than 0.1 seconds to give the results. I have done research on this throughout last week and I couldn't find a proper solution. Here is my code.
public List<ResponseDto> loadData(RequestDto request) throws SQLException {
List<ResponseDto> responseDto = new ArrayList<>();
int sortBy = request.getSortBy();
String sql = "SELECT *" +
"FROM (SELECT r.*, ROWNUM RNUM, COUNT(*) OVER () RESULT_COUNT " +
" FROM (SELECT *" +
"FROM" +
" (SELECT r.VALUE_4," +
" r.DATE," +
" r.ID," +
" r.AMOUNT," +
" r.TO_AGENT_ID," +
" r.FROM_AGENT_ID," +
" a.NAME," +
" r.VALUE_2," +
" r.VALUE_1," +
" r.STATUS," +
" r.VALUE_3," +
" r.TEXT" +
" FROM MY_TABLE r" +
" INNER JOIN AGENT a " +
" ON a.AGENT_ID=r.TO_AGENT_ID" +
" WHERE r.STATUS = 1 " +
" AND r.ID IN" +
" (SELECT T.ID FROM TEST_TABLE T" +
" INNER JOIN AGENT af" +
" ON af.AGENT_ID = T.FROM_AGENT_ID " +
" INNER JOIN AGENT at" +
" ON at.AGENT_ID=T.TO_AGENT_ID" +
" WHERE T.FROM_AGENT_ID=?";
StringBuilder sbQuery = new StringBuilder(sql);
if (request.getToAgentId() != 0) {
sbQuery.append(" AND T.TO_AGENT_ID = ? ");
} else if (request.getQueryParam() != null && !request.getQueryParam().equalsIgnoreCase("")) {
sbQuery.append(" AND UPPER(at.NAME) like UPPER( ? ) ");
}
String secondPart =
" AND T.STATUS = 1" +
" AND TO_DATE(T.DATE) BETWEEN TO_DATE(?, 'yyyy-MM-dd') AND TO_DATE(?, 'yyyy-MM-dd')" +
" ) " +
" or r.VALUE_3=?";
sbQuery.append(secondPArt);
if (sortBy == 1) {
sbQuery.append(" ORDER BY a.NAME ");
} else if (sortBy == 2) {
sbQuery.append(" ORDER BY r.AMOUNT ");
} else if (sortBy == 3) {
sbQuery.append(" ORDER BY r.VALUE_4 ");
}
if (request.getSortingOrder() == 1) {
sbQuery.append("DESC ");
} else if (request.getSortingOrder() == 2) {
sbQuery.append("ASC ");
}
sbQuery.append(" )) R)" +
"WHERE RNUM between ? and ?");
String sqlq = sbQuery.toString();
log.info(sqlq);
try(Connection con = dataSource.getConnection(); PreparedStatement pstmt = con.prepareStatement(sbQuery.toString()) ) {
con.setAutoCommit(false);
String nameParam = "%" + request.getQueryParam() + "%";
pstmt.setLong(1, request.getFromAgentId());
if (request.getToAgentId() != 0) {
pstmt.setLong(2, request.getToAgentId());
} else if(request.getQueryParam() != null && !request.getQueryParam().equalsIgnoreCase("")) {
pstmt.setString(2, request.getQueryParam());
}
pstmt.setString(3, request.getFromDate());
pstmt.setString(4, request.getToDte());
pstmt.setString(5, request.getQueryParam());
pstmt.setLong(6, request.getFromIndex());
pstmt.setLong(7, request.getToIndex());
responseDto = helperMethod(pstmt);
con.commit();
} catch (SQLException e) {
log.error(e.getMessage());
throw e;
}
return responseDto;
}
public List<MyDto> helperMethod(PreparedStatement pstmt) throws SQLException {
List<MyDto> myDtoList = new ArrayList<>();
try( ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
MyDto myDto = new MyDto();
myDto.setValue4(rs.getLong("VALUE_4"));
myDto.setDate(rs.getDate("DATE"));
myDto.setTransactionId(rs.getLong("ID"));
myDto.setAmount(rs.getLong("AMOUNT"));
myDto.setToAgentId(rs.getLong("TO_AGENT_ID"));
myDto.setFromAgentId(rs.getLong("FROM_AGENT_ID"));
myDto.setName(rs.getString("NAME"));
myDto.setValue2(rs.getLong("VALUE_2"));
myDto.setValue1(rs.getLong("VALUE_1"));
myDto.setStatus(rs.getInt("STATUS"));
myDto.setValue3(rs.getString("VALUE_3"));
myDto.setText(rs.getString("TEXT"));
myDtoList.add(myDto);
}
}catch (Exception ex){
log.error(ex.getMessage());
throw ex;
}
return myDtoList;
}
As I said, same query works with in milliseconds. I really don't know what i am doing wrong here.
Any help would be grateful !
This is not a direct answer, but may hopefully point you in the right direction. First off, depending on your conditionals, there are different variations of what SQL is executed. I would try the following:
Edit the select string and embed a unique comment in it so we can find it in the next step. Example : "select /*mytest*/ * from ..."
Execute your program. Then locate the query in the v$sqlarea such as: select sql_id from v$sqlarea where instr(sql_fulltext,'mytest') > 0;
using the sql_id value from Step #2, execute SELECT * FROM table(DBMS_XPLAN.DISPLAY_CURSOR('sql_id',0));
this will show you the execution plan, and hopefully you will see the difference maybe a full table scan is happening or index not getting used. etc. Do similar steps for the direct sql query that is faster and see what the differences are.

oracle pass list of string as parameter

I want to pass list of string as parameter
when my query is generated from my application I have this sql code :
SELECT * FROM Transfers TRANSFERS
LEFT OUTER JOIN correspondence_copy CORRESPCPY on CORRESPCPY.ID_COPY = TRANSFERS.ID_COPY
WHERE TRANSFERS.ORDERNBR in ('[236359981, 236359982, 236359983]')
this is the source code in jave where I used List
public List<SupEntity> sendSup(List<String> listOrderNumber)
throws Exception {
String query_tr = " SELECT * ";
query_tr += " FROM Transfers TRANSFERS ";
query_tr +=" LEFT OUTER JOIN correspondence_copy CORRESPCPY on CORRESPCPY.ID_COPY = TRANSFERS.ID_COPY " ;
query_tr +=" WHERE TRANSFERS.ORDERNBR in ('" +listOrderNumber + "')";
SQLQuery sqlQuery = this.getSession().createSQLQuery(query_tr);
sqlQuery.setResultTransformer(Transformers.aliasToBean(
SupEntity.class));
List list = sqlQuery.list();
return list;
}
I call this methode from this code :
public SupListEntity getsupList(
HttpServletRequest request,
SupListEntity supListEntity)
throws Exception {
List<String> list = new ArrayList<String>();
List<CorrespondenceEntity> sendsupList =new ArrayList<SupEntity>();
String [] tabOrder=null;
if(supListEntity.getId()!=null)
{
tabOrder=supListEntity.getId().split(",");
if(tabOrder!=null && tabOrder.length>0)
{
for(int i=0;i<tabOrder.length;i++)
{
list.add(tabOrder[i]);
}
sendsupList = supDAO.sendSup(list);
supListEntity.setCorrespondenceList(sendsupList);
}
}
return supListEntity;
}
so the problem that my query which is generaed has this kind of code :
in ('[236359981, 236359982, 236359983]') which is false
it should be like this
in ('236359981', '236359982', '236359983')
You may try this:
String query_tr = " SELECT * ";
query_tr += " FROM Transfers TRANSFERS ";
query_tr +=" LEFT OUTER JOIN correspondence_copy CORRESPCPY on CORRESPCPY.ID_COPY = TRANSFERS.ID_COPY " ;
query_tr +=" WHERE TRANSFERS.ORDERNBR in (:list)";
SQLQuery sqlQuery = this.getSession().createSQLQuery(query_tr);
sqlQuery.setParameterList("list", listOrderNumber)

Oracle vs Oracle ODBC

The following code works fine from within Oracle's SqlPlus (using Oracle 11.2.02.0g) however when I connect with and ODBC connection via C# code, I get told I have an invalid character.
Since the single quote didn't work in SQLplus, I'm assuming the characters that are consider invalid by ODBC are the double quotes. I've tried braces '{' and brackets '[' but still get the same error -> ERROR [HY000][Oracle][ODBC][Ora]ORA-00911:invalid character <-
Any help would be much appreciated. I still don't understand why SQL statements would be interpreted differently because of the connection type.
CREATE USER "AD1\EGRYXU" IDENTIFIED EXTERNALLY;
Error if ran alone that states the username conflicts with another user or role name. It does create the user in the database.
C# Code is below.
private void button1_Click(object sender, EventArgs e)
{
string happy = "";
string sql1 = "";
string sql2 = "";
string sql3 = "";
string sql4 = "";
string column;
int rownum = -1;
bool frst = false;
string dirIni = "\\\\ramxtxss021-f01\\hou_common_013\\globaluser\\";
string fileIni = "add_users.sql";
string transIniFullFileName = Path.Combine(dirIni, fileIni);
System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection();
num_users = (usrdetails.Count > 0);
if (regions && num_users)
{
using (StreamWriter sw = new StreamWriter(transIniFullFileName))
{
for (int y = 0; y < usrdetails.Count; y++)
{
switch(usrdetails[y].add_del.ToUpper())
{
case "A":
sql1 = "CREATE USER \"" + usrdetails[y].userID.ToUpper() + "\" IDENTIFIED EXTERNALLY;";
sql2 = "GRANT EDMROLE TO \"" + usrdetails[y].userID.ToUpper() + "\";";
sql3 = "INSERT INTO MD_SITE_USER VALUES(generate_key(5), (select user_id from MD_SITE_USER where user_name = '" +
usrdetails[y].group + "') , {" + usrdetails[y].userID.ToUpper() + "}, " + usrdetails[y].seclev +
", '" + usrdetails[y].username.ToUpper() + "', 'U', '" + usrdetails[y].isext.ToUpper() + "', 'N');";
sw.WriteLine(sql1);
sw.WriteLine(sql2);
sw.WriteLine(sql3);
break;
case "D":
sql2 = "DELETE MD_SITE_APP_ACTION_OWNER WHERE user_id in (SELECT user_id FROM MD_SITE_USER where user_name = ‘"+ usrdetails[y].userID + "’+ and user_or_group = ‘U’);";
sql3 = "DELETE FROM MD_SITE_USER where user_name = ‘"+ usrdetails[y].userID + "’ and user_or_group = ‘U’;";
sql4 = "DROP USER "+ usrdetails[y].userID + " FROM USERS;";
sw.WriteLine(sql2);
sw.WriteLine(sql3);
sw.WriteLine(sql4);
break;
default:
MessageBox.Show("Add/Delete command argument not recognized for user\r\n" + usrdetails[y].userID + " \r\n Argument -> " + usrdetails[y].add_del);
break;
}
}
sw.Close();
}
for (int x = 0; x < region.Count; x++)
{
OdbcCommand command = new OdbcCommand();
conn.ConnectionString = "Driver={Oracle in OraClient11g_home1};" +
"Dbq=" + region[x].dbname +
";Uid=" + region[x].username + ";Pwd=" + region[x].password + ";";
try
{
string cmdTexts = File.ReadAllText(transIniFullFileName);
conn.Open();
using (conn)
{
command.Connection = conn;
command.CommandText = cmdTexts;
command.ExecuteNonQuery();
OdbcDataReader dr = command.ExecuteReader();
Form6.dataGridView2.AutoGenerateColumns = false;
if (!frst)
{
for (int i = 0; i < dr.FieldCount; i++)
{
column = dr.GetName(i);
Form6.dataGridView2.Columns.Add("col" + i, column);
Form6.dataGridView2.Columns[i].FillWeight = 1;
}
frst = true;
}
rownum++;
dataGridView1.Rows.Add();
dataGridView1.Rows[rownum].Cells[0].Value = "Results for Region -> " + Form5.region[x].dbname;
dataGridView1.Refresh();
while (dr.Read())
{
rownum++;
Form6.dataGridView2.Rows.Add();
for (int i = 0; i < dr.FieldCount; i++)
{
column = dr.GetValue(i).ToString();
Form6.dataGridView2.Rows[rownum].Cells[i].Value = column;
}
}
Form6.dataGridView2.Refresh();
Form6.dataGridView2.Show();
Form6.Show();
}
conn.Close();
Form6.dataGridView2.Refresh();
}
catch (Exception ex)
{
MessageBox.Show("Error Message: " + ex.Message);
}
}
}
else
{
if (!regions)
happy = "Error - You have not selected any regions.\r\n";
else
happy = "Regions are now selected.\r\n";
if (!num_users)
happy = happy + "Error - You have not entered any users.\r\n";
MessageBox.Show(happy);
}
File.Delete(transIniFullFileName);
}
Don't use ";" (semi-colon) in the command text..
The command text within ODBC or ODP should be a command, e.g. not a set of commands, therefore - ";" is not relevant, and is an invalid character.
it appears you are trying to run a script..
if that is your intent, it should be padded with a "begin" and "end" for the code to be able to run:
BEGIN
INSERT...;
DELETE ...;
END;
(refer to http://www.intertech.com/Blog/executing-sql-scripts-with-oracle-odp/ for more info)
Last thing - if you want to run a "create user" (or any other DDL) from within an anonymous block or a procedure you need to run it with "execute immediate" syntax:
BEGIN
execute immediate 'CREATE USER test IDENTIFIED EXTERNALLY';
END;